如何使用FormData进行离子文件上传 [英] How to use FormData for ionic file upload

查看:222
本文介绍了如何使用FormData进行离子文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用fileTransfer(ionic 3)或其他功能将表单数据发送到服务器

i want to send formdata to server with fileTransfer(ionic 3 ) or other function

var form = new FormData();
form.append("filedata", base64File);
form.append("numDeclaration", "01012018");

let options: FileUploadOptions = {
          fileKey: 'filedata',
          fileName: imageName,
          chunkedMode: false,
          mimeType: "image/jpeg",
          headers: {}
        }

fileTransfer.upload(base64File, 'http://localhost:8080/alfresco/api/-default-/public/alfresco/versions/1/nodes/f3589d6b-82db-44d2-9b6d-89a3e7e57442/children?alf_ticket=' + localStorage.getItem('token'), options).then((data) => {
     console.log(data + " Uploaded Successfully");
}

推荐答案

我认为您无需使用cordova文件传输插件.您可以只通过有角度的HttpClient(XMLHttpRequest)发送FormData.您只需要将base64字符串转换为blob对象,即可将其进一步上传到服务器上.

I think it’s not necessary to use cordova file transfer plugin in your case. You can just send FormData through angular HttpClient (XMLHttpRequest). You just need to convert base64 string into blob object which you can to upload further on your server.

class UploadService {
  constructor(private httpClient: HttpClient) {
    const base64 = 'data:image/png;base64,';
    this.uploadBase64(base64, 'image.png').subscribe(() => {});
  }

  uploadBase64(base64: string, filename: string): Observable<any> {
    const blob = this.convertBase64ToBlob(base64);
    const fd = new FormData();

    fd.append('filedata', blob, filename);
    fd.append('numDeclaration', '01012018');

    return this.httpClient.post('url', fd)
      .pipe(catchError((error: any) => Observable.throw(error.json())));
  }

  private convertBase64ToBlob(base64: string) {
    const info = this.getInfoFromBase64(base64);
    const sliceSize = 512;
    const byteCharacters = window.atob(info.rawBase64);
    const byteArrays = [];

    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
      const slice = byteCharacters.slice(offset, offset + sliceSize);
      const byteNumbers = new Array(slice.length);

      for (let i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
      }

      byteArrays.push(new Uint8Array(byteNumbers));
    }

    return new Blob(byteArrays, { type: info.mime });
  }

  private getInfoFromBase64(base64: string) {
    const meta = base64.split(',')[0];
    const rawBase64 = base64.split(',')[1].replace(/\s/g, '');
    const mime = /:([^;]+);/.exec(meta)[1];
    const extension = /\/([^;]+);/.exec(meta)[1];

    return {
      mime,
      extension,
      meta,
      rawBase64
    };
  }
}

这篇关于如何使用FormData进行离子文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆