在 ReactJS 中将 PDF 编码为 base64

IT技术 reactjs base64
2021-05-05 04:28:52

请帮我!如何在react中将文件编码为字符串 base64

handleUploadFile(event) {
  let file = event.target.files[0]

  // here encoding file base64?

  this.setState({
    fileData: file,
    fileName: file.name
  })
}
1个回答

以下是您可以尝试的内容:

handleUploadFile(event) {
    let selectedFile = event.target.files;
    let file = null;
    let fileName = "";
    //Check File is not Empty
    if (selectedFile.length > 0) {
        // Select the very first file from list
        let fileToLoad = selectedFile[0];
        fileName = fileToLoad.name;
        // FileReader function for read the file.
        let fileReader = new FileReader();
        // Onload of file read the file content
        fileReader.onload = function(fileLoadedEvent) {
            file = fileLoadedEvent.target.result;
            // Print data in console
            console.log(file);
        };
        // Convert data to base64
        fileReader.readAsDataURL(fileToLoad);
    }

  this.setState({
    fileData: file,
    fileName: fileName
  })
}

不过,您可能需要为多个文件更改它。