简体   繁体   中英

Convert byte[] to file javascript

I have the byte array in javascript. How convert this array to file for upload?

"

What I got from your question is that you have a Byte Array and you want to write these Byte Array to a file and upload it to server.

No, It is not possible in JavaScript because JavaScript doesn't have access to writing files as this would be a huge security risk.

you create a file like this

new File([you byte here], 'name of your file', { type: 'you extention', lastModified: new Date() });

if the your byte is string 

  new File([this.base64ToArrayBuffer(you string)], 'file name', { type: this.handleFileDataType(DocExtension), lastModified: new Date() });



 base64ToArrayBuffer = (base64) => {
    var binaryString = window.atob(base64);
    var binaryLen = binaryString.length;
    var bytes = new Uint8Array(binaryLen);
    for (var i = 0; i < binaryLen; i++) {
      var ascii = binaryString.charCodeAt(i);
      bytes[i] = ascii;
    }
    return bytes;
  }



 handleFileDataType = ext => {
    switch (ext) {
      case 'pdf':
        return 'application/pdf';
      case 'jpg':
        return 'image/jpeg';
      case 'jpeg':
        return 'image/jpeg';
      case 'png':
        return 'image/png';
      case 'tiff':
        return 'image/tiff';
      case 'docx':
        return 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
    }
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM