Skip to content Skip to sidebar Skip to footer

Uploading Image Using Javascript

I'm stuck!! :( I want to upload image file with a title and a caption, I want to use javascript for validation of title caption and a file choosen. My html goes here:

Solution 1:

In order to access files with the $_FILES superglobal they need to be sent with a multipart/form-data content-type header and appropriate attributes. Unfortunately you cannot do this with xhr's send method manually because sending a string will be automatically converted to UTF-8. Fortunately though you can still send binary data such as a file from javascript's window.File.

This is not supported in older browsers. The code would look like

var file = document.getElementById('photo').files[0];

...

xhr.send(file);

And then on the server side you will need to access the input buffer directly in order to grab a hold of this file

$file = file_get_contents('php://input');

If you insist on using $_FILES you could use the FormData object in javascript. The reason I left this as a second option is because I've heard about greater support issues and I personally avoid using it for now.

var formData = newFormData(document.getElementById('theForm'));
...
xhr.send(formData);

EDIT 2016

It has been some time now since I posted this answer and now the FormData object is widely supported, if you are looking to upload files along with other data you may look into that.

Solution 2:

You are trying to upload an image with ajax... short answer... normally you can't. You need a multipart/form-data to upload, making ajax upload a pain.

An easy work around would be to validate the form with js, then normally submit it. Like here: Ajax Upload image - well... ignore the title, is misleading.

Post a Comment for "Uploading Image Using Javascript"