问题描述
我正在尝试将Base64编码的图像添加到字符串数组.使用通过react-bootstrap的FormControl创建的文件输入表单:
I am attempting to add Base64 encoded images to a string array. Using a file input form created with react-bootstrap's FormControl:
<FormControl
type="file"
values={this.state.files}
multiple
onChange={this.addImage.bind(this)}
/>
我正在调用此函数:
addImage(event) {
var newArr = [];
for(var i=0; i<event.target.files.length; i++) {
newArr.push(this.getBase64(event.target.files[i])));
}
this.setState({ files: newArr });
}
对图像进行编码的功能如下:
The function which encodes the images looks like this:
getBase64(file) {
var reader = new FileReader();
reader.onloadend = function() {
return reader.result
}
reader.readAsDataURL(file);
}
当addImage()函数调用getBase64()函数时,返回的值是 undefined .我相信这是由于getBase64()函数开始运行所引起的.当我添加console.log行以吐出reader.result时,base64字符串将正确输出到控制台,但是返回的值显然仍然相同.
When the addImage() function calls the getBase64() function the returned value is undefined. I believe this is caused from the time it takes the getBase64() function to run. When I add a console.log line to spit out the reader.result the base64 string is output to the console properly, but the returned value is still, obviously, the same.
这是怎么回事,如何才能正确返回实际的base64字符串?
What is going on here and how can I get the actual base64 string returned properly?
推荐答案
在事件处理程序中,异步地提供结果的事件处理程序中,getBase64
函数未同步返回任何值. FileReader
loadend
事件异步返回结果.您可以使用Promise.all()
或async/await
来获取getBase64()
函数调用
No value is returned from getBase64
function synchronously from within an event handler which provides results asynchronously. FileReader
loadend
event returns results asynchronously. You can use Promise.all()
or async/await
to get value returned asynchronously from getBase64()
function call
class ReadFiles {
constructor() {}
async addImage(event) {
const newArr = [];
for (let i = 0; i < event.target.files.length; i++) {
newArr.push(
await this.getBase64(event.target.files[i])
);
}
const o = {
files: newArr
};
console.log(o);
}
getBase64(file) {
return new Promise(function(resolve) {
var reader = new FileReader();
reader.onloadend = function() {
resolve(reader.result)
}
reader.readAsDataURL(file);
})
}
}
let reader = new ReadFiles();
document.querySelector("input[type=file]")
.onchange = e => reader.addImage.call(reader, e);
<input type="file" multiple>
这篇关于Javascript base64编码函数返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!