我正在尝试这样做:
var http = new XMLHttpRequest();
var url = "guardarImg.php";
var params = $('#form').serialize();
http.open("POST", url, true);
http.setRequestHeader("Content-type", "multipart/form-data");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
但是没有用,它在我的php中显示我没有定义'Image',但是当我通过平均提交时它工作正常。
我看到的所有类似样本都使用字符串数据,但我需要使用图像来实现它,以便以后在英特尔XDK中使用
我做错了什么? 你能告诉我一个样品吗?
很抱歉,如果我的问题太基础了,我就是一个带有xmlhttp和ajax东西的菜鸟。
答案 0 :(得分:1)
你对$("#form")。serialize()有正确的想法,但对于(仍然)AJAX上传的混乱。哎呀(因为第一次没注意到这个细节而感到羞耻:-()。
通过AJAX上传文件的问题(通常就是这种情况),Internet Explorer。基本上,它在IE10之前不支持FormData对象(这意味着,如果你关心支持XP用户,他们最好不要运行IE-IE)。 FormData极大地简化了通过AJAX上传内容的过程;如果您没有,请选择以下选项:
我会假设你不关心IE8 / 9(几乎所有人都不是问题)并给你一个FormData解决方案。与之前的编辑不同,我在这里弹出整个功能,因为它提供了相当丰富的信息。此特定解决方案上载整个表单,将现有字段拉入FormData对象并专门处理文件。
<!-- Many ways to skin this particular feline; I like this one :-) -->
<form onsubmit="return uploadFiles(this)">
<!-- Access from PHP using $_FILES["somefile"]["name"][$idx]... -->
<input type="file" name="somefiles" multiple="1" />
</form>
<script>
// Function to upload a form via FormData, breaking out files and cutting
// any non-named elements. Assumes that there's a #status DIV and the
// URL is hardcoded.
function uploadFiles(frm) {
var formdata = new FormData();
// I'm doing this to separate out the upload content. Note that multiple
// files can be uploaded and will appear as a decently-friendly PHP array
// in $_FILES. Note also that this does handle multiple files properly
// (a default FormData(frm) wouldn't exactly :-( ).
$(frm).find(":input").each(function(idx, ele) {
// This is a file field. Break it out.
if(ele.files) {
for(i=0; i<ele.files.length; i++) {
formdata.append(ele.name + "[" + i + "]", ele.files[i]);
}
// Not a file element, so put in the upload iff there's a name.
} else if(ele.name) {
formdata.append(ele.name, ele.value);
}
});
// Run the AJAX.
$.ajax({
url: "test.php", // Change Me :-)
type: "POST",
data: formdata,
processData: false, // Need these to keep jQuery from messing up your form
contentType: false,
success: function(data) {
$("#status").html(data);
},
error: function(xhr, status, error) {
$("#status").html("Error uploading file(s): " + error);
},
});
return false; // Keep the form from submitting
}
</script>
我有一个完整的HTML文件和相应的PHP,可以在pastebin工作。
如果我是你,我实际上只是使用Sebastian's jQuery File Upload,如果可以的话。它拥有所有现代UI优点(包括进度计量),浏览器抽象以及MIT授权启动。也就是说,如果你只是需要一些copypasta的话,这个答案会帮助你。祝你好运!