【发布时间】:2017-11-08 09:43:32
【问题描述】:
我在 React 中进行了注册,我需要将文件上传到服务器。这些文件需要进行 Base64 编码。
对其进行编码的函数如下:
getBase64(file) {
let document = "";
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
document = reader.result;
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
return document;
}
处理点击表单下一个按钮的函数如下:
handleNextButtonClick(event){
event.preventDefault();
let data = {domainId: this.props.user[0].domainId, name: steps.stepThree, values: this.state.files};
let idCard = this.state.files.filter(file => file.file_type === "ID_CARD")[0].values.file;
let statuses = this.state.files.filter(file => file.file_type === "STATUTES")[0].values.file;
let blankLetterHead = this.state.files.filter(file => file.file_type === "LETTER_HEAD")[0].values.file;
let companyPhoto = this.state.files.filter(file => file.file_type === "COMPANY_PICTURE")[0].values.file;
let idCardBase64 = this.getBase64(idCard);
let statusesBase64 = this.getBase64(statuses);
let blankLetterHeadBase64 = this.getBase64(blankLetterHead);
let companyPhotoBase64 = this.getBase64(companyPhoto);
}
如果我控制台记录例如第一个 this.state.files.filter(file => file.file_type === "ID_CARD")[0].values.file; 我得到 p>
一切似乎都很好,但我遇到了错误:
Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
知道如何解决这个问题吗?
更新
let idCardBase64 = idCard ? this.getBase64(idCard) : "";
let statusesBase64 = statuses ? this.getBase64(statuses) : "";
let blankLetterHeadBase64 = blankLetterHead ? this.getBase64(blankLetterHead) : "";
let companyPhotoBase64 = companyPhoto ? this.getBase64(companyPhoto) : "";
我改了。在这种情况下只存在idCard。现在我没有收到任何错误,但 idCardBase64 是 "" 而不是 Base64 编码。
【问题讨论】:
-
文件读取代码看起来正确。你能验证所有 4 个文件都存在吗?
-
@AjaySuvarna 我更新了我的问题。
-
可能与您在/从状态中存储/过滤数据的方式有关?你能举一个州的例子吗?比如
statuses = this.state.files.filter(file => file.file_type === "STATUTES"),这应该是STATUSES还是STATUTES? -
文件读取是异步的,所以getBase64函数返回的是空字符串。
标签: javascript reactjs base64 filereader