【问题标题】:How to get byte array from a file in reactJSreactjs如何从文件中获取字节数组
【发布时间】:2019-09-23 20:18:00
【问题描述】:

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

<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>

这就是我尝试在uploadedImage 函数中使用ReadAsBinaryString 的方式:

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)
}

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

【问题讨论】:

  • 你想做什么?您想在不将头像上传到服务器的情况下显示头像吗?
  • 这是错误的var array = new Uint32Array(file); 您正在使用file 信息变量来读取数据,而不是您应该使用传递给处理程序的data
  • @DacreDenny 我正在尝试获取图像,然后将其作为字节数组发送到服务器,你看到字节数组是我必须发送到后端 API 的数据的一部分,我的意思是由于后端限制,我必须将文件转换为字节数组,这是必须的

标签: javascript reactjs html


【解决方案1】:

只是为了补充 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 函数中完成...

【讨论】:

    【解决方案2】:

    这种方法对我有用:

    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

    【讨论】:

    • 转换成二进制后如何查看返回响应和文件日期?
    【解决方案3】:

    您正在尝试使用包含文件信息而不是文件内容file 变量读取文件数据。尝试如下:

    FileReader documentation

    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)
    }
    

    【讨论】:

      猜你喜欢
      • 2013-11-23
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      • 2018-10-10
      • 2012-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多