Xhr send a base64 string and decode it on the server to a file


I am trying to send img to base64 to the server, javascript looks like

var xhr=new XMLHttpRequest() var reader=new FileReader() reader.onloadend=function(e){ xhr.onload=function(e){ alert(xhr.responseText) } xhr.open("POST","upload.php"); xhr.setRequestHeader("Cache-Control", "no-cache"); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); //xhr.setRequestHeader("X-File-Name", file.name); //xhr.setRequestHeader("X-File-Type",file.type) xhr.send(e.target.result) } reader.readAsDataURL(file) },false) 


In php it looks like this:

 echo "some response Text"; $postdata = file_get_contents("php://input"); file_put_contents('MyFile.jpg', base64_decode($postdata)); 

And in the end, the server receives the file exactly the size of the sent file, but it cannot be opened
Does anyone get some ideas? Thank you very much!

+4
source share
1 answer
 reader.readAsDataURL(file) 

The data URL is NOT the same as the base64 file version. You get excess garbage. It looks like this:

 data:[<MIME-type>][;charset=<encoding>][;base64],<data> 

See Wikipedia .

Try making a simple regular expression on it:

 var data = dataURL.match(/,(.*)$/)[1]; 

Or, in your code,

 xhr.send(e.target.result.match(/,(.*)$/)[1]); 
+18
source

All Articles