最简单的使用FormData() https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects class:
现在您有了一个 FormData 对象,可以与 XMLHttpRequest 一起发送。并使用 FormData 对象附加字段
<script type="text/javascript">
$(document).ready(function () {
var form = $('form'); //valid form selector
form.on('submit', function (c) {
c.preventDefault();
var data = new FormData();
$.each($(':input', form ), function(i, fileds){
data.append($(fileds).attr('name'), $(fileds).val());
});
$.each($('input[type=file]',form )[0].files, function (i, file) {
data.append(file.name, file);
});
$.ajax({
url: '/post_url_here',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (c) {
//code here if you want to show any success message
}
});
return false;
});
})
</script>
并强制 jQuery 不要为您添加 Content-Type 标头,否则,上传文件边界字符串将丢失。