我在AJAX POST中设置我的标题并且POSTing工作正常,但请求有效负载正文没有按照我的意图格式化。
for (var i = 0; i < files.length; i++) {
var boundary = '--AJAX--' + b.util.randomString();
var fileName = files[i].fileName;
var fileSize = files[i].fileSize;
var fileType = files[i].type;
var parts = [];
var part = '';
part += 'Content-Disposition: file;' + CRLF;
part += 'name= "' + fieldName + '"; ' + CRLF;
part += 'filename="' + fileName + '"' + CRLF;
part += 'Content-Type: ' + fileType + ';' + CRLF;
part += 'name="' + 'timestamp' + '"' + CRLF + CRLF;
part += getDateTime() + CRLF;
parts.push(part);
var data = '--' + boundary + CRLF;
data += parts.join('--' + boundary + CRLF);
data += '--' + boundary + '--' + CRLF;
// Wrap in a closure to preserve our increment value [i]
(function(i) {
files = $.extend(true, {}, files);
$.ajax({
url: $form,
type: 'POST',
beforeSend: function(xhr) {
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.setRequestHeader('X-File-Name', fileName);
xhr.setRequestHeader('X-File-Size', fileSize);
xhr.setRequestHeader('X-File-Type', fileType);
},
data: {
userfile: data
},
success: function(data) {
},
error: function(e) {
}
});
})(i);
}
格式化为:
/*
userfile=--AJAX-----------------------------2Bw0sHPkE4%0D%0AContent-Disposition%3A+file%3B%0D%0Aname%3D+%22userfile%5B%5D%22%3B+filename%3D%22MPK0l.jpg%22%0D%0AContent-Type%3A+image%2Fjpegname%3D%22timestamp%22%0D%0A%0D%0A1330556315.828%0D%0A--AJAX-----------------------------2Bw0sHPkE4--%0D%0A
*/
显然无视我的所有换行和回车。
我是否必须显式创建我的xhr对象并使用xhr.send()或者我可以使用jQuery的ajax()吗?
答案 0 :(得分:0)
来自RFC1867的一些引言:
如果选择了多个文件,则应将它们一起传输 使用multipart / 混合格式。
内容类型:multipart / form-data * , * boundary = AaB03x comma is used, not a semicolon
毕竟,我不确定,可以通过xhr准备原始POST数据。
答案 1 :(得分:0)
决定创建XHR对象,而不是使用jQuery的ajax()
。
for (var i = 0, f; f = files[i]; i++) {
(function(i) {
var xhr = new XMLHttpRequest();
var reader = new FileReader();
xhr.open('POST', $form, true);
reader.onload = function(e) {
var boundary = '--AJAX--' + b.util.randomString();
var binaryFile = e.target.result;
var fileName = files[i].fileName;
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.setRequestHeader('X-File-Name', files[i].fileName);
xhr.setRequestHeader('X-File-Size', files[i].fileSize);
xhr.setRequestHeader('X-File-Type', files[i].type);
var parts = [];
var part = '';
part += 'Content-Disposition: file; ';
part += 'name="' + fieldName + '"' + CRLF;
part += 'Content-Type: ' + files[i].type;
part += CRLF + 'Content-Transfer-Encoding: binary' + CRLF + CRLF;
part += binaryFile + CRLF;
parts.push(part);
part = 'Content-Disposition: form-data; ';
part += 'name="' + 'timestamp' + '"' + CRLF + CRLF;
part += getDateTime() + CRLF;
parts.push(part);
var data = '--' + boundary + CRLF;
data += parts.join('--' + boundary + CRLF);
data += '--' + boundary + '--' + CRLF;
xhr.sendAsBinary(data);
};
reader.readAsBinaryString(files[i]);
})(i);
}