Javascript 如何在 React 中将文件转换为 Base64

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47176280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:46:07  来源:igfitidea点击:

How to convert files to Base64 in React

javascriptreactjsbase64filereader

提问by Boky

I have registration for in React where I need to upload files to the server. Those files needs to be Base64 encoded.

我在 React 中注册了我需要将文件上传到服务器的地方。这些文件需要 Base64 编码。

The function to encode it is as follows:

对其进行编码的函数如下:

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;
    }

And function to handle click on form's next button is as follow:

处理单击表单下一个按钮的功能如下:

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);
}

If I console log for example the first one this.state.files.filter(file => file.file_type === "ID_CARD")[0].values.file;I get

如果我控制台日志例如this.state.files.filter(file => file.file_type === "ID_CARD")[0].values.file;我得到的第一个

enter image description here

在此处输入图片说明

Everything seems ok, but I'm getting error:

一切似乎都很好,但我收到错误消息:

Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.

Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.

Any idea how to solve this?

知道如何解决这个问题吗?

UPDATE

更新

let idCardBase64 = idCard ? this.getBase64(idCard) : "";
let statusesBase64 = statuses ? this.getBase64(statuses) : "";
let blankLetterHeadBase64 = blankLetterHead ? this.getBase64(blankLetterHead) : "";
let companyPhotoBase64 = companyPhoto ? this.getBase64(companyPhoto) : "";

I changed it. And in this case exists only idCard. Now I do not get any errors but idCardBase64is ""and not Base64 encoded.

我改变了它。而在这种情况下只存在idCard. 现在,我没有得到任何错误,但idCardBase64就是""不Base64编码。

回答by Ajay Dharnappa Poojary

file reading is asynchronous. so use callback or promise to solve your problem.

文件读取是异步的。所以使用回调或承诺来解决你的问题。

let idCardBase64 = '';
this.getBase64(idCard, (result) => {
     idCardBase64 = result;
});

and use callback to return the data which you get.

并使用回调返回您获得的数据。

getBase64(file, cb) {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
        cb(reader.result)
    };
    reader.onerror = function (error) {
        console.log('Error: ', error);
    };
}

回答by Mostafa Nawara

Also, you can use this React component React File Base64

此外,您可以使用这个 React 组件React File Base64

Check the demo

检查演示