Abhijeet Abhijeet - 4 months ago 85
Javascript Question

Send Image to server using File input type

I have a screen where I am capturing video from camera, taking a snap. I also have a file input and I want to set this option to the captured image from the camera, i.e..snap.

I do not want to store the snap as a cookie and later retrieve it, as it will later make the users computer heavy and will require cleaning everytime.

so the code is

<input type="file" id="visitorphoto" name="visitorPhoto" accept="image/*" capture>


which is according to this w3 document.

Any Ideas using javascript?

Thanks,
Abhijeet.

Answer

Use formData to upload file. HTML:

<input type="file" id="filechooser">

Javascript Code

function uploadFile() {
    var blobFile = $('#filechooser').files[0];
    var formData = new FormData();
    formData.append("fileToUpload", blobFile);

    $.ajax({
       url: "upload.php",
       type: "POST",
       data: fd,
       processData: false,
       contentType: false,
       success: function(response) {
           // .. do something
       },
       error: function(jqXHR, textStatus, errorMessage) {
           console.log(errorMessage); // Optional
       }
    });
}

Compatibility: http://caniuse.com/xhr2

Comments