Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use FormData for ionic file upload

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");
}
like image 427
Grenoblois Avatar asked Feb 10 '26 08:02

Grenoblois


2 Answers

I got into the same problem, and did not wanted to use ionic file transfer plugin.

I read the file as blob and added that in formData. Worked fine for me.

private fileReader(file: any) {
  const reader = new FileReader();
  reader.onloadend = () => {
    const formData = new FormData();
    const blobFile = new Blob([reader.result], { type: file.type });
    formData.append("file", blobFile, "filename");
    // POST formData call
  };
  reader.readAsArrayBuffer(file);
}
like image 76
K.S Avatar answered Feb 16 '26 13:02

K.S


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
    };
  }
}
like image 26
WinGood Avatar answered Feb 16 '26 14:02

WinGood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!