【发布时间】:2011-11-23 15:45:19
【问题描述】:
我的 javascript 函数只能正确上传文本文件。谁能帮我弄清楚如何让它也接受图像等?
function fileUpload(files) {
if (!files.length) {
fileList.innerHTML = "<p>No files selected!</p>";
} else {
var list = document.createElement("ul");
for (var i = 0; i < files.length; i++) {
//Set vars
var file = files[i],
fileName = file.name,
fileSize = file.size,
fileData = file.getAsBinary(),
boundary = "xxxxxxxxx",
uri = "receive.php",
//Create file info HTML output
li = document.createElement("li");
list.appendChild(li);
var info = document.createElement("span");
info.innerHTML = file.name + ": " + file.size + " bytes";
li.appendChild(info);
//Start sending file
var xhr = new XMLHttpRequest();
xhr.open("POST", uri, true);
xhr.setRequestHeader("Content-Type", "multipart/form-data, boundary="+boundary); // simulate a file MIME POST request.
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if ((xhr.status >= 200 && xhr.status <= 200) || xhr.status == 304) {
if (xhr.responseText != "") {
alert(xhr.responseText); // display response.
}
}
}
}
var body = "--" + boundary + "\r\n";
body += "Content-Disposition: form-data; name='upload'; filename='" + fileName + "'\r\n";
body += "Content-Type: application/octet-stream\r\n\r\n";
body += fileData + "\r\n";
body += "--" + boundary + "--";
xhr.send(body);
}
fileList.appendChild(list);
return true;
}
}
更新:我在http://code.google.com/p/html5uploader/ 在线找到了以下函数,但我不知道如何将它应用到我当前的函数中。 xhr.sendAsBinary 是唯一改变的东西吗?
// Upload image files
upload = function(file) {
// Firefox 3.6, Chrome 6, WebKit
if(window.FileReader) {
// Once the process of reading file
this.loadEnd = function() {
bin = reader.result;
xhr = new XMLHttpRequest();
xhr.open('POST', targetPHP+'?up=true', true);
var boundary = 'xxxxxxxxx';
var body = '--' + boundary + "\r\n";
body += "Content-Disposition: form-data; name='upload'; filename='" + file.name + "'\r\n";
body += "Content-Type: application/octet-stream\r\n\r\n";
body += bin + "\r\n";
body += '--' + boundary + '--';
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary=' + boundary);
// Firefox 3.6 provides a feature sendAsBinary ()
if(xhr.sendAsBinary != null) {
xhr.sendAsBinary(body);
*snip*
【问题讨论】:
-
如何检索文件。我的意思是文件参数必须在某处提供。你是怎样做的?我需要对这个通过 ajax 上传文件的主题进行一些解释。任何帮助将不胜感激。
-
@user1698985 我不确定你的意思,你的意思是在 PHP 端检索它吗?在这种情况下,您可以在 POST 数据中找到它。
-
在服务器端检索它是另一个讨论。我只想找到在加载到表单数据并通过 ajax 发送的客户端上选择文件的方式。在 Html5 中很容易。但我不明白它在以前版本的 html 中是怎样的。我试图查看 ajaxform 插件,但很难理解它是如何检索文件数据并通过 ajax 发送的。我想了解整个过程,从选择文件到在 jquery 中处理并提交到服务器。
-
在您的帖子中,您将文件参数发送到函数。您从哪里获得以及如何将值输入文件参数?
-
我真的不明白你的意思..这是一个参数。你在调用函数时提供它,然后你可以在函数中使用它,但我猜这不是你的意思。在函数中,文件数据被加载并添加到 POST 正文中,然后将其发送到脚本。您对此不了解的到底是什么?