http - Ionic 3 文件传输多部分/表单数据

标签 http post ionic-framework multipartform-data file-transfer

我实际上正在使用 ionic v3 和 angular5 开发移动应用程序

目标是能够拍摄照片或从现有照片中进行选择,然后将其上传到服务器。第一部分已完成,但我在上传方面遇到困难。

API 需要 multipart/form-data,它必须包含两个请求。第一个是文本部分,第二个是图像。

有什么解决办法吗?

最佳答案

这是我针对类似要求所做的

takePhoto() {
    this.camera.getPicture({
      quality: 100,
      destinationType: this.camera.DestinationType.FILE_URI,
      sourceType: this.camera.PictureSourceType.CAMERA,
      encodingType: this.camera.EncodingType.PNG,
      saveToPhotoAlbum: true
    }).then(imageData => {
      this.myPhoto = imageData;
      this.uploadPhoto(imageData);
    }, error => {
      this.functions.showAlert("Error", JSON.stringify(error));
    });
  }

  selectPhoto(): void {
    this.camera.getPicture({
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
      destinationType: this.camera.DestinationType.FILE_URI,
      quality: 100,
      encodingType: this.camera.EncodingType.PNG,
    }).then(imageData => {
      this.myPhoto = imageData;
      this.uploadPhoto(imageData);
    }, error => {
      this.functions.showAlert("Error", JSON.stringify(error));
    });
  }
  private uploadPhoto(imageFileUri: any): void {
    this.file.resolveLocalFilesystemUrl(imageFileUri)
      .then(entry => (<FileEntry>entry).file(file => this.readFile(file)))
      .catch(err => console.log(err));

  }
  private readFile(file: any) {
    const reader = new FileReader();
    reader.onloadend = () => {
      const formData = new FormData();
      const imgBlob = new Blob([reader.result], { type: file.type });
      formData.append('evaluationID', this.currentEvaluation.evaluationId);
      formData.append('standardID', this.currentEvaluation.id);
      formData.append('score', this.currentEvaluation.score);
      formData.append('comment', this.currentEvaluation.comment);
      formData.append('file', imgBlob, file.name);
      this.saveStandard(formData);
    };
    reader.readAsArrayBuffer(file);
  }

这是提供者的代码

saveStandard(receivedStandardInfo:any){
    return new Promise((resolve, reject) => {
      this.http.post(apiSaveStandard,receivedStandardInfo)
        .subscribe(res => {
          resolve(res);
        }, (err) => {
          console.log(err);
          reject(err);
        });
    }).catch(error => { console.log('caught', error.message); });
  }

关于http - Ionic 3 文件传输多部分/表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48451452/

相关文章:

spring - Spring 休息中的健康或状态端点

php - POST 文件上传 - multipart/form-data + PHP 中的 UTF 错误?

wordpress - wp_rewrite 在插件设置页面中返回 null

javascript - 在图像缩放期间禁用滑动器

angularjs - 显示错误 - "Blink deferred a task in order to make scrolling smoother"

http - 将应用上传到谷歌应用引擎时出现问题

java - spring 拦截器不向@RestController 服务添加 header

html - 是通过表单在 HTML 中传递 POST 参数的唯一方法吗?

javascript - 如何通过 jQuery POST 请求发送原始字符串?

ios - 错误 错误 : Uncaught (in promise): MyPlugin does not have web implementation