0

我在javascript中有字节数组。如何将此数组转换为文件进行上传?

4

2 回答 2

0

我从您的问题中得到的是您有一个字节数组,并且您想将这些字节数组写入文件并将其上传到服务器。

不,这在 JavaScript 中是不可能的,因为 JavaScript 无权写入文件,因为这将是一个巨大的安全风险。

于 2013-01-09T09:21:23.703 回答
0

你创建一个这样的文件

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';
    }
  };
于 2022-02-02T20:12:37.933 回答