我有一個HTML上傳按鈕,用於將(多個)文件發送到使用JSON響應的服務器。基於這種迴應,我的申請流程繼續進行。模擬XHR2文件上傳
現在,爲了測試我的代碼的其餘部分(取決於服務器的響應),我想模擬文件上傳,這樣我就不必在每次重新加載時手動選擇並上傳新文件。
以下是我上傳方法的簡化版本:
uploadToServer: function (file) {
var self = this,
data = new FormData(),
xhr = new XMLHttpRequest();
// When the request has successfully completed.
xhr.onload = function() {
var response = $.parseJSON(this.responseText);
var photo = new App.Models.Photo({
filename: response.filename,
name: response.uuid
});
var photoView = new App.Views.Photo({ model: photo });
$('.photos').append(photoView.render().el);
};
// Send to server, where we can then access it with $_FILES['file].
data.append('file', file);
xhr.open('POST', this.url);
xhr.send(data);
}
的uploadToServer
參數file
從FileList一個File -object。正如你所看到的,我的服務器正在等待$_FILES['file']
中的文件。
這將是真棒,如果可以模擬一個真實的文件對象被傳遞到uploadToServer
,因爲我再也不擔心我現有的事件,如xhr.onload
和xhr.onprogress
可用。
如果這樣做不可行,我可以創建自定義uploadToServer
方法,並在我的服務器上發送常規的AJAX請求和假響應。但是,我該如何使用綁定我的事件(xhr.onload
,xhr.onprogress
等)的代碼到該AJAX請求?
非常感謝nikoshr,我還沒有聽說過呢。我發現一個Blob構造函數也適用,而不是Canvas-to-Blob.js。 你有沒有機會知道如何傳遞文件名?因爲'_FILES ['file'] ['name']'總是讀取_blob_。 –
對於畫布到Blob,我玩它安全:)看起來似乎formData.append接受第三個參數,一個文件名。 'formData.append('file',blob,fileName);'參見http://stackoverflow.com/questions/6664967/how-to-give-a-blob-uploaded-as-formdata-a-file-name – nikoshr