Browse - Programming Tips - How can I upload a file with jQuery?

Date: 2017dec21
Language: javaScript
Library: jquery

Q.  How can I upload a file with jQuery?

A.

html:
<input type='file' id='myfile'>
javaScript:
var formdata = new FormData(); var myfile = $('#myfile')[0]; // Get the DOM object with id=myfile var fileObj = myfile.files[0]; // Get the first in files array formdata.append('myfile', fileObj);
$.ajax({ url: 'put-your-url-here', type: 'post', data: formdata, cache: false, contentType: false, processData: false, dataType: 'text', // or json if your server side returns that success: function(data, textStatus, jqXHR) { // to-do }, error: function onUploadError(jqXHR, textStatus, errorThrown) { // to-do }, });