Input type = "file" set base64 image data

I have a canvas and extract image data from it using canvas.toDataURL('image/png') .

Problem: <input type="file" /> asks for the file path as value instead of base64 data.

Question: How to send base64 image data to the server using <input type="file" /> WITHOUT saving it in the local file system?

My workarounds: Tried hidden input <input type="file" /> , but the server requires a file name property

Could it be possible to overcome this with XmlHttpRequest?

+7
javascript html ajax html5-canvas
source share
2 answers

Just create a hidden input element in your form. (note the type)

 <input type="hidden" name="myHiddenField"> 

Attach your data to the item value before submitting.

 var imageData = canvas.toDataURL('image/png'); document.getElementsByName("myHiddenField")[0].setAttribute("value", imageData); 

UPDATE

If your server requires a file name parameter in the data provided, include this line as the name of the input element.

 <input type="hidden" name="filename"/> 

This will trick the form into submitting your data with the "filename" parameter included.

If you want to use XMLHttpRequest for this, follow the example:

 //Prepare data to be sent var imageData = canvas.toDataURL('image/png'); var params = "filename=" + imageData; //Initiate the request var httpRequest = new XMLHttpRequest(); httpRequest.open('POST', 'test.php', true); //Send proper headers httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); httpRequest.setRequestHeader("Content-length", params.length); httpRequest.setRequestHeader("Connection", "close"); //Send your data httpRequest.send(params); 
+8
source share
0
source share

All Articles