【发布时间】:2014-03-10 19:10:10
【问题描述】:
编辑 我正在尝试通过 jQuery / ajax() 发送几个输入值,其中包含一个文件,而 ajax() 似乎并不同时支持两者。我发现 FormData 可以解决问题。 Using jQuery ajax to upload file and form data with formData() http://www.thefourtheye.in/2013/10/file-upload-with-jquery-and-ajax.html
更新 我不再有任何错误,但文件未正确上传到 MySQL DB/LongBlob 列中。现在似乎在 PHP 文件中正确接收了它。
html
<input type=hidden name=catselid id=catselid value=".$id.">
<input name=city id=city>
<input name=country id=country>
<input type=file name=picture id=picture >
<input name=update value=update type=submit class=update id=update />
javascript
$(".update").click(function(){
$.ajax({
url: 'catsel_change.php',
type: 'POST',
contentType:false,
processData: false,
data: function(){
var data = new FormData();
data.append('picture',$('#picture').get(0).files[0]);
data.append('city' , $('#cityname').val());
data.append('country', $('#country').val());
data.append('id', $('#catselid').val());
return data;
}(),
success: function(result) {
alert(result);
},
error: function(xhr, result, errorThrown){
alert('Request failed.');
}
});
});
php
if(is_uploaded_file($_FILES['picture']['tmp_name'])){
$picture =addslashes (file_get_contents($_FILES['picture']['tmp_name']));
...
}
仅供参考,我使用的是 jQuery 1.9.1 欢迎cmets/建议 问候
【问题讨论】:
-
试试看这个答案:stackoverflow.com/questions/166221/… :)
-
malsup.com/jquery/form/#ajaxSubmit 发送带有文件的表单的 ajax/iframe 方法。