【问题标题】:Convert byte[] to file javascript将 byte[] 转换为文件 javascript
【发布时间】:2013-01-09 09:11:17
【问题描述】:

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

【问题讨论】:

标签: javascript file bytearray


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你创建一个这样的文件

    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';
        }
      };
    

    【讨论】:

      猜你喜欢
      • 2021-08-20
      • 2011-11-04
      • 2011-06-08
      • 2014-07-21
      • 1970-01-01
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      相关资源
      最近更新 更多