如何从reactJS中的文件获取字节数组 [英] How to get byte array from a file in reactJS

查看:446
本文介绍了如何从reactJS中的文件获取字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got a form for uploading Avatar image and I have to send the image file in the format of binary string; so far I've tried ReadAsBinaryString from FileReader but it's not working:( here's my code:

<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的方式:

and that is how I'm trying to use ReadAsBinaryString in uploadedImage function:

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

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

so to sum it up, I get a file but I can't convert it to byte array; Is there anything wrong with this code or this approach is completely wrong?

推荐答案

此方法对我有用:

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/zh-CN/docs/Web/API/FileReader

You can call reader.readAsBinaryString() if you wish to use binary string. More here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader

这篇关于如何从reactJS中的文件获取字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆