我有一个微服务(在NancyFx中),它可以按照以下cURL命令的预期工作:
curl --verbose --form file=@"C:\test\image.png" http://localhost:8080/file/upload
该文件按预期显示在Nancy内:
context.Request.Files[0] //The file bytes are here, yeah!!
现在,我必须让我的网络客户端以相同的方式将选定的文件发送到同一服务。
TLDR;如果您想要
,可以跳过下面的失败示例我已经尝试了以下几个版本但没有成功:
var uploadForm = new FormData();
// Add the file to the request.
uploadForm.append("file", file, name);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:8080/file/upload', true);
xhr.onload = function() {
if (xhr.status === 200)
alert('File ' + name + 'Upload successfully!!!');
else errorFn("Upload Failure on file " + name);
};
//Send the data
xhr.send(uploadForm);
以下几个版本也没有成功:
var postConfig = {
url: 'http://localhost:8080/file/upload',
data: uploadForm,
processData: false, //tries without this as well
type: "POST",
dataType: "application/x-www-form-urlencoded; charset=UTF-8",
cache: false,
success: successFn,
error: errorFn
}
$.ajax(postConfig);
我已用
尝试了上述内容使用以下代码设置文件:
var reader = new FileReader();
reader.onload = function (result) {
var fileContent = new Uint8Array(result.target.result);
var encContent = new SP.Base64EncodedByteArray();
for (var b = 0; b < fileContent.length; b++) {
encContent.append(fileContent[b]);
}
<Set file = encContent and send AJAZ as above>
};
reader.readAsArrayBuffer(fileInput);
如何从javascript(jQuery或标准)提交此文件,以便它像cURL一样工作?
答案 0 :(得分:0)
这是最终有效的代码。 (不可否认,我以为我已经尝试过这个,并在我的问题中这么说)
var file = $('MyFileSelectorControl').files[0];
var uploadForm = new FormData();
// Add the file to the request.
uploadForm.append("file", file, name);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:8080/file/upload', true);
xhr.onload = function() {
if (xhr.status === 200)
alert('File ' + name + 'Upload successfully!!!');
else errorFn("Upload Failure on file " + name);
};
//Send the data
xhr.send(uploadForm);