【问题标题】:Can't post image from ionic to express server using php无法使用 php 从 ionic 发布图像到 express 服务器
【发布时间】:2017-05-10 20:30:17
【问题描述】:

我正在尝试将图片从 ionic 应用程序上传到快速服务器。当我使用邮递员对其进行测试时,服务器运行良好,但是从 ionic 视图来看它不起作用(无法在 iPhone 上测试,因为我没有 Mac)。

代码如下:

import { ActionSheetController, ToastController, Platform, LoadingController, Loading } from 'ionic-angular';
import { Injectable } from '@angular/core';
import { ApiService } from '../services/api.service';

import { File } from '@ionic-native/file';
import { Transfer, TransferObject } from '@ionic-native/transfer';
import { FilePath } from '@ionic-native/file-path';
import { Camera } from '@ionic-native/camera';
import { Http, Headers } from '@angular/http';
declare var cordova: any;

@Injectable()
export class imageService {
  loading: Loading;
  image: string = null;
  imageSelected: Boolean = false;
  constructor(private http: Http, private camera: Camera, private transfer: Transfer, private file: File, private filePath: FilePath, public actionSheetCtrl: ActionSheetController, public toastCtrl: ToastController, public platform: Platform, public loadingCtrl: LoadingController) { }




  takePicture(sourceType) {
    // Create options for the Camera Dialog
    var options = {
      destinationType: this.camera.DestinationType.DATA_URL,
      quality: 50,
      sourceType: sourceType,
      saveToPhotoAlbum: false,
      correctOrientation: true
    };

    // Get the data of an image
    this.camera.getPicture(options).then((imageData) => {
      this.image = "data:image/jpeg;base64," + imageData;
      this.presentToast('Selected Image');
      alert("selected image");
      this.imageSelected = true;
      this.uploadImage();
    }, (err) => {
      this.presentToast('Error while selecting image.');
      alert("error selecting");
    });
  }



  private presentToast(text) {
    let toast = this.toastCtrl.create({
      message: text,
      duration: 3000,
      position: 'top'
    });
    toast.present();
  }


  uploadImage() {
    if (this.imageSelected) {
      this.presentToast("image is selected");
      alert("image is selected");
      this.http.post("http://appserver.com:8080/sql_api/profilePic", { image: this.image }, function(err, res){
        if(err){
          console.log("ERROR", err);
          alert("Error with request");
        }else{
          console.log(res);
          alert("success in callback");
          this.presentToast('image posted successfully');
        }
      });
    }
    else {
      this.presentToast('image not selected');
      alert("image not selected");
    }
  }


}

使用它时,我没有收到来自服务器日志的任何发布请求。

【问题讨论】:

    标签: javascript angular http ionic-framework


    【解决方案1】:

    这里没有提供服务器代码或邮递员请求标头信息,因此我假设您的服务器可以处理 json 请求。

    您的代码有什么问题

      uploadImage() {
        if (this.imageSelected) {
          this.presentToast("image is selected");
          alert("image is selected");
    
        /* http method on angular is not a simple callback 
        its an observable and this request missing headers also
        this request will not executed if you not calling subsribe on angular 
        http */
        this.http.post("http://appserver.com:8080/sql_api/profilePic",{ image: this.image }, function(err, res){
          if(err){
            console.log("ERROR", err);
            alert("Error with request");
          }else{
            console.log(res);
            alert("success in callback");
            this.presentToast('image posted successfully');
          }
        });
    
        /* change your request like this and make sure your express server 
        can handle json request and parse the body
        you can look at express body parser to handle another request */
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        this.http.post("http://appserver.com:8080/sql_api/profilePic",
        { image: this.image },{headers:headers})
        .subscribe((res)=>{
            // request success here is your response
            console.log(res);
            alert("success in callback");
            this.presentToast('image posted successfully');
          },
          err =>{
          // handler error
            console.log("ERROR", err);
            alert("Error with request");
          }
        )
      }
    } 
    

    我建议您制作另一个组件或离子页面以将 ui 组件与 imageService 分开。因为 UI 交互不应该在 Angular 服务中。

    image-service.ts

    import { Injectable } from '@angular/core'; 
    import { Http, Headers } from '@angular/http';
    
    @Injectable()
    export class ImageService {
    
     constructor(private http: Http ) { }
    
     uploadImage(image) {
       let headers = new Headers();
       headers.append('Content-Type', 'application/json');
       return this.http.post("http://appserver.com:8080/sql_api/profilePic",{ 
       image: image },{headers:headers});
     }
    }
    

    ImagePage.ts

      import { Component } from '@angular/core';
      import { NavController, NavParams, AlertController, LoadingController, ActionSheetController, ToastController, Platform,Loading} from 'ionic-angular';
      import { ImageService } from './image-service';
      import { Camera } from '@ionic-native/camera';
    
      /*
        Generated class for the ImagePage.
    
        See http://ionicframework.com/docs/v2/components/#navigation for more info on
        Ionic pages and navigation.
      */
      @Component({
        selector: 'app-image',
        templateUrl: 'image.html',
        providers: [ImageService]
      })
      export class ImagePage {
        loading: Loading;
        image: string = null;
        imageSelected: Boolean = false;
    
        constructor(private camera: Camera,  public actionSheetCtrl: 
        ActionSheetController, public toastCtrl: ToastController, 
        public platform: Platform, public loadingCtrl: LoadingController,
        private imageService:ImageService) {}
    
        takePicture(sourceType) {
          // Create options for the Camera Dialog
          var options = {
            destinationType: this.camera.DestinationType.DATA_URL,
            quality: 50,
            sourceType: sourceType,
            saveToPhotoAlbum: false,
            correctOrientation: true
          };
    
          // Get the data of an image
          this.camera.getPicture(options).then((imageData) => {
            this.image = "data:image/jpeg;base64," + imageData;
            this.presentToast('Selected Image');
            alert("selected image");
            this.imageSelected = true;
            this.imageService.uploadImage(this.image)
                .subscribe((res)=>{
                  // request success here is your response
                  console.log(res);
                  alert("success in callback");
                  this.presentToast('image posted successfully');
                },
                err =>{
                // handler error
                  console.log("ERROR", err);
                  alert("Error with request");
                });
            }, (err) => {
              this.presentToast('Error while selecting image.');
              alert("error selecting");
            });
        }
    
        private presentToast(text) {
          let toast = this.toastCtrl.create({
            message: text,
            duration: 3000,
            position: 'top'
          });
          toast.present();
        }
      }
    

    测试

    如果你没有在真实硬件上测试它,使用 ionic serve 确保通过访问这个 ionic 博客 Handling CORS issues in Ionic 来处理 cors 问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-12
      • 2021-12-06
      • 2018-08-05
      • 2018-08-31
      • 1970-01-01
      • 1970-01-01
      • 2015-09-13
      • 1970-01-01
      相关资源
      最近更新 更多