我有一个上传Avatar图片的表格,我必须以二进制字符串格式发送图片文件;到目前为止,我已经尝试过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)
}
总而言之,我得到了一个文件,但无法将其转换为字节数组;这段代码有什么问题吗?或者这种方法是完全错误的?
答案 0 :(得分:1)
这种方法对我有用:
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
答案 1 :(得分:0)
您正尝试使用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)
}