Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/418.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Can';t使用php将图像从ionic发布到express服务器_Javascript_Angular_Http_Ionic Framework - Fatal编程技术网

Javascript Can';t使用php将图像从ionic发布到express服务器

Javascript Can';t使用php将图像从ionic发布到express服务器,javascript,angular,http,ionic-framework,Javascript,Angular,Http,Ionic Framework,我正在尝试将图片从ionic应用程序上载到express服务器。当我使用postman测试服务器时,它运行良好,但是从ionic的角度来看,它不工作(无法在iPhone上测试,因为我没有mac) 代码如下: import { ActionSheetController, ToastController, Platform, LoadingController, Loading } from 'ionic-angular'; import { Injectable } from '@angular

我正在尝试将图片从ionic应用程序上载到express服务器。当我使用postman测试服务器时,它运行良好,但是从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");
    }
  }


}

我在使用服务器日志时没有收到任何post请求

这里没有提供服务器代码或邮递员请求头信息,因此我假设您的服务器可以处理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服务中

图像服务.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});
 }
}
  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();
    }
  }
ImagePage.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});
 }
}
  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博客来处理cors问题