How to convert a String to actual file that was generated from FileReader.readAsDataURL()

狂风中的少年 提交于 2019-12-11 06:36:28

问题


I have generated a string of a file using this:

const reader = new window.FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
  var x = reader.result.toString();
  console.log("File String :: ", x);
};

How to convert this string to actual file like if the previous file was a PDF then this string will converted to a pdf file

reader.result.toString() gives me a string like this "data:application/pdf;base64,JVBERi0xLjQKJSDi48/..........."

I want to convert it back to pdf

FileReader.readAsDataURL()


回答1:


If you have a base64 string use atob to decode it and then use the Blob() constructor to get a Blob object (super constructor to File)

//strip off the data uri prefix
let encodedString = dataUrlString.replace('data:application/pdf;base64,','')
let data = atob(encodedString);
let blob = new Blob([data],{'type':'optional mime type here'});

//if you need a literal File object
let file = new File(blob,"filename.pdf",{type:"optional mime type"});



回答2:


It cannot be done, you want to send data to the server, but cannot be doing so with javascript. youre going to have to incorporate PHP or similar to accomplish the file creation on the server.

Javascript is a client-side language. with javascript, there is no way to send a string or file to the server. its not connected to it. what youre actually doing is having the client read his own file. the server has no notion nor should it ever see what your client is uploading via javascript.

If you want to create the file on the clients computer, why are you creating a file from a file upload on the clients own computer? the client could have just copied it themselves by right clicking the file.

See my other answer here for more detail: Old SO answer



来源:https://stackoverflow.com/questions/59110683/how-to-convert-a-string-to-actual-file-that-was-generated-from-filereader-readas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!