Home how to post image data through javascript

# how to post image data through javascript

Liam Sorsby
1#
Liam Sorsby Published in 2013-04-17 08:25:18Z
 I have a html form which sends POST data to my PHP script It also uses AJAX to provide a preview as they complete the form However the form uses onsubmit="" The issue i have is one of the html inputs is an image. the form is as below to give you an idea: 

 I am using var logo =document.getElementById("logo").value; for the image but when i am sending the logo value through to PHP it breaks the image as it isn't the correct post value required to be sent through to the PHP script as though you are submitting the form. Does anyone know how to get the same post value for the logo html field simply by using onchange and javascript?
Arnelle Balane
2#
Arnelle Balane Reply to 2013-04-17 08:56:24Z
 If I understood it correctly, you just want to display a preview of the image as the file input's value gets changed, right? If so, I guess want you want to do is just to load a preview of the image from the user's local drive, without it really uploaded to your server yet. The actual file upload can be done when the user already submits the form. To do the said process (loading a preview of the image file), HTML5's FileReader API. Using the FileReader API is actually simple, and it can be done like so: Javascript var logo = document.getElementById("logo").files[0]; // will return a File object containing information about the selected file // File validations here (you may want to make sure that the file is an image) var reader = new FileReader(); reader.onload = function(data) { // what you want to do once the File has been loaded // you can use data.target.result here as an src for an img tag in order to display the uplaoded image someImageElement.src = data.target.result; // assume you have an image element somewhere, or you may add it dynamically } reader.readAsDataURL(logo);  You can place this code inside your onchange event handler, and I guess you won't be needing AJAX in here. Then when the form gets submitted, the image data can be obtained in its usual place, in the $_FILES array. Community 3# Community Reply to 2017-05-23 11:43:18Z  I think you have to upload the file to your server for preview too if you can't use the html5 features (f)open your $_FILES['userfile']['tmp_name'] and sends it raw contents back, see: How can I use \$.ajax to set image src to dynamic image/png data?. You can resize the image before sending the data back and delete the image afterwards.
 You need to login account before you can post.
Processed in 0.31005 second(s) , Gzip On .