Last active
March 29, 2021 12:30
-
-
Save greenyleaf/ba91c1b1b90b37e00b645f199e2ced6b to your computer and use it in GitHub Desktop.
Upload files using ajax. Using FormData only if there are file fields in the form, to reduce the upload size when not needed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.ajax('http://custom.sdrkyj.top/form-action-url', { | |
contentType: hasFiles ? false : undefined, | |
data: hasFiles ? new FormData(formDom) : $(formDom).serialize(), | |
method: 'post',// 'patch' | |
dataType: 'json', | |
processData: !hasFiles, | |
xhr: function () { | |
let xhr = $.ajaxSettings.xhr(); | |
hasFiles && xhr.upload.addEventListener('progress', function (e) { | |
if (e.lengthComputable && e.total > 1 << 17) { | |
const percentage = Math.round((e.loaded * 100) / e.total) + '%'; | |
// show upload progress, use `percentage` variable | |
} | |
}); | |
return xhr; | |
}, | |
success: function (data, textStatus, jqXHR) { | |
$(formDom).find('input[type=file]').val(''); // clear file form fields | |
}, | |
complete: function (jqXHR, textStatus, errorThrown) { | |
//show upload complete | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment