【发布时间】:2012-12-26 22:31:04
【问题描述】:
我有一个 HTML 上传按钮,用于将(多个)文件发送到以 JSON 响应的服务器。根据该响应,我的申请流程将继续。
现在,为了测试我的其余代码(取决于服务器响应),我想模拟文件上传,这样我就不必在每次重新加载时手动选择和上传新文件。
以下是我的上传方法的简化版:
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 对象。如您所见,我的服务器等待$_FILES['file'] 中的文件。
如果可以模拟一个真实的文件对象被传递到uploadToServer,那就太棒了,因为这样我就不必担心我现有的事件,例如xhr.onload 和xhr.onprogress 可用。
如果这不可能,我可以创建一个自定义的uploadToServer 方法并在我的服务器上发送一个常规的 AJAX 请求和假响应。但是,我怎样才能使用我的事件(xhr.onload、xhr.onprogress 等)中的代码并将其绑定到该 AJAX 请求?
【问题讨论】:
标签: javascript backbone.js xmlhttprequest