如何从reactJS中的文件中获取字节数组

IT技术 javascript reactjs html
2021-05-17 10:15:33

我有一个上传头像的表格,我必须以二进制字符串的格式发送图像文件;到目前为止,我已经尝试过ReadAsBinaryStringFileReader但它不起作用:(这是我的代码:

<form onSubmit={this.onFormSubmit}>
      <div className="row justify-content-center mb-2">
           <input type="file" id="avatar"  accept="image/png, image/jpeg" 
            onChange={this.uploadedImage} />
           <button type="submit" className="btn btn-sm btn-info">Send</button>
       </div>
  </form>

这就是我试图ReadAsBinaryStringuploadedImage函数中使用的方式

uploadedImage(e) {
    let reader = new FileReader();
    let file = e.target.files[0];
    console.log(file); //I can see the file's info
    reader.onload= () => {
        var array = new Uint32Array(file);
        console.log("_+_array:",array); // the array is empty!
        var binaryString = String.fromCharCode.apply(null,array) ;
        console.log("__binaryString:",binaryString);
      this.setState({
        file: binaryString
      },()=>{
        console.log(this.state.file);//ergo file is set to an empty image
    });
    }
    reader.readAsArrayBuffer(file)
}

总而言之,我得到了一个文件,但无法将其转换为字节数组;这段代码有什么问题还是这种方法完全错误?

3个回答

这种方法对我有用:

function readFileDataAsBase64(e) {
    const file = e.target.files[0];

    return new Promise((resolve, reject) => {
        const reader = new FileReader();

        reader.onload = (event) => {
            resolve(event.target.result);
        };

        reader.onerror = (err) => {
            reject(err);
        };

        reader.readAsDataURL(file);
    });
}

reader.readAsBinaryString()如果你想使用二进制字符串,你可以调用更多信息:https : //developer.mozilla.org/en-US/docs/Web/API/FileReader

您正在尝试使用file包含文件信息而不是文件内容变量读取文件数据像下面这样尝试某事:

文件阅读器文档

uploadedImage(e) {
    let reader = new FileReader();
    let file = e.target.files[0];
    console.log(file); //I can see the file's info
    reader.onload= () => {
        var array = new Uint32Array(reader.result); // read the actual file contents
        console.log("_+_array:",array); // the array is empty!
        var binaryString = String.fromCharCode.apply(null,array) ;
        console.log("__binaryString:",binaryString);
      this.setState({
        file: binaryString
      },()=>{
        console.log(this.state.file);//ergo file is set to an empty image
    });
    }
    reader.readAsArrayBuffer(file)
}

只是为了添加tomericco的答案,这里有几行以获得实际的最终字节数组:

 const test_function = async () => {

      ... ... ...

      const get_file_array = (file) => {
          return new Promise((acc, err) => {
              const reader = new FileReader();
              reader.onload = (event) => { acc(event.target.result) };
              reader.onerror = (err)  => { err(err) };
              reader.readAsArrayBuffer(file);
          });
       }
       const temp = await get_file_array(files[0])
       console.log('here we finally ve the file as a ArrayBuffer : ',temp);
       const fileb = new Uint8Array(fileb)

       ... ... ...

  }

file直接File你想读取对象在哪里,这必须在一个async函数中完成......