我的javascript功能只能正確上傳文本文件。任何人都可以幫我弄清楚如何讓它也接受圖像等?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來解釋這個文件上傳的問題。任何幫助將不勝感激。 – user1575229
@ user1698985我不確定你的意思,你的意思是在PHP端檢索它?在這種情況下,您可以在POST數據中找到它。 – natli
在服務器端檢索它是另一個討論。我只想找到加載到表單數據並通過ajax發送的客戶端上選擇文件的方式。在Html5中很容易。但我不明白它是如何在以前的版本的HTML。我試圖窺探ajaxform插件,但很難理解它是如何檢索文件數據並通過ajax發送的。我想了解整個過程,從jquery中選擇文件到處理並提交給服務器。 – user1575229