【发布时间】: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