使用表单数据的Ionic 3发布图像

时间:2019-02-27 03:47:04

标签: php angular ionic3

我正在尝试将包含文本和图像文件的表单数据发布到PHP服务器。 我使用离子本机相机从图库中获取图片:

const options: CameraOptions = {
    quality: 70,
    destinationType: this.camera.DestinationType.FILE_URI,
    sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
    saveToPhotoAlbum:false,
    targetWidth: 400,
    targetHeight: 400
}

this.camera.getPicture(options).then((imageData) => {
  this.myphoto = normalizeURL(imageData);
  this.myphoto2 = imageData;
}, (err) => {

});

并使用表单数据将其发布:

var headers = new Headers();
headers.append('Content-Type', 'multipart/form-data;boundary=' + Math.random());
headers.append('Accept', 'application/json');
let options = new RequestOptions({
    headers: headers
});
let formData = new FormData();
formData.append('judul', this.judul.value);
formData.append('photo', this.myphoto, '123.jpg');
this.http.post('http://localhost/upload.php', formData, options)
    .map(...)
    .subscribe(...);

但是,我在PHP日志中看到,表单数据不是由ionic发送的。 怎么了?

3 个答案:

答案 0 :(得分:1)

  1. 您可以尝试从this.http.post()参数中删除“选项”。 您的代码变为:

    this.http.post('http://localhost/upload.php',formData)     。地图(...)     .subscribe(...);

  2. 如果这不起作用, 尝试使用

    在整个BASE64图像上发送

    'destinationType:this.camera.DestinationType.DATA_URL'

答案 1 :(得分:0)

我建议您使用本机插件上传文件:

https://ionicframework.com/docs/native/file-transfer/

答案 2 :(得分:0)

首先从相机拍照

async takePhoto() {
const options: CameraOptions = {
    quality: 70,
    destinationType: this.camera.DestinationType.FILE_URI,
    sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
    saveToPhotoAlbum:false,
    targetWidth: 400,
    targetHeight: 400
}

this.camera.getPicture(options).then((imageData) => {
  this.getSystemURL(imageData);
}, (err) => {

});
}

比获取本地系统映像URL

private getSystemURL(imageFileUri: any): void {
    this.file.resolveLocalFilesystemUrl(imageFileUri)
        .then(entry => (entry as FileEntry).file(file => {
          this.readFile(file);
        }))
        .catch(err => console.log(err));
  }

读取该图像网址后

private readFile(file: any) {
    const reader = new FileReader();
    reader.onloadend = () => {
      this.myphoto = new Blob([reader.result], {type: file.type});
      var headers = new Headers();
headers.append('Content-Type', 'multipart/form-data;boundary=' + Math.random());
headers.append('Accept', 'application/json');
let options = new RequestOptions({
    headers: headers
});
let formData = new FormData();
formData.append('judul', this.judul.value);
formData.append('photo', this.myphoto, '123.jpg');
this.http.post('http://localhost/upload.php', formData, options)
    .map(...)
    .subscribe(...);
    };
    reader.readAsArrayBuffer(file);
  }

它为我工作, 希望对您有所帮助。