Programming Tips - jQuery: upload a file

Date: 2017dec21 Language: javaScript Library: jquery Q. jQuery: upload a file A. html:
<input type='file' id='myfile'>
var formdata = new FormData(); const myfile = $('#myfile')[0]; // Get the DOM object with id=myfile const 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 }, });
If you also have text fields in the form, add then *before* the file.
formdata.append('note', 'Hello there'); formdata.append('myfile', fileObj);