通过jQuery ajax提交包含文件上传的表单 [英] Submit form including file upload via jQuery ajax
本文介绍了通过jQuery ajax提交包含文件上传的表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
HTML:
<input type="text" name="description">
<input type="file" name="image" accept=".jpg">
如何使用 $。ajax
来上传图片和文字值?我没有问题生成一个提交文本数据的对象,但不知道从哪里开始使用图像。
How can I use $.ajax
to upload the image and text value? I have no problem producing an object to submit text data, but have no idea where to start with the image.
我正在使用PHP服务器端,因此对图像进行编码在base64或类似方法中是完全可以接受的。
I am using PHP server-side, so encoding the image in base64 or similar methods are perfectly acceptable.
推荐答案
最简单的方法是使用 FormData()
class:
it’s easiest to use the FormData()
class:
所以现在你有了一个FormData对象,随时可以与XMLHttpRequest一起发送。并使用FormData对象附加字段
So now you have a FormData object, ready to be sent along with the XMLHttpRequest. and append fields with FormData Object
<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标头,否则,上传文件边界字符串将丢失。
这篇关于通过jQuery ajax提交包含文件上传的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文