我有一个上传头像的表格,我必须以二进制字符串的格式发送图像文件;到目前为止,我已经尝试过ReadAsBinaryString
,FileReader
但它不起作用:(这是我的代码:
<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>
这就是我试图ReadAsBinaryString
在uploadedImage
函数中使用的方式:
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)
}
总而言之,我得到了一个文件,但无法将其转换为字节数组;这段代码有什么问题还是这种方法完全错误?