0

I am trying to read an image using HTML input of type = 'File'. After the user selects the file, i wish to make a POST request to a particular URL. This POST request should have the image selected by the user. I have looked into jQuery Ajax calls without any success. The link which I am trying to hit expects an image as byte array.

1 Answer 1

2

Try this:

html:

<input id="pic" type="file" name="pic" />
<button id="upload">Upload</button>

Jquery:

$('#upload').on('click', function() {
    var file_data = $('#pic').prop('files')[0];
    var form_data = new FormData();
    form_data.append('file', file_data);

    $.ajax({
            url         : 'upload.php',     // point to server-side PHP script 
            dataType    : 'text',           // what to expect back from the PHP script, if anything
            cache       : false,
            contentType : false,
            processData : false,
            data        : form_data,                         
            type        : 'post',
            success     : function(output){
                alert(output);              // display response from the PHP script, if any
            }
    });
});
4
  • Lovely. This works. But i realize now that I don't wish to make it an ajax call. Can you please help me converting this into a $.post() call? I guess everything else remains the same. The URL that I am hitting processes the image and returns JSON data. So i don't want to make an ajax call. Thanks!
    – Harshil
    Commented Apr 18, 2017 at 6:55
  • But i realize now that I don't wish to make it an ajax call why is it so ? Commented Apr 18, 2017 at 6:57
  • The UI will continuously flash "Processing your request please wait" once the image is uploaded. If I keep it ajax, the execution continues and i cannot achieve the desired UI.
    – Harshil
    Commented Apr 18, 2017 at 7:01
  • Just added one option in the same ajax request. async : false does the job. Thank you, Mayank!
    – Harshil
    Commented Apr 18, 2017 at 8:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.