我有以下 JavaScript 来为上传过程设置进度条
$(document).ready(function () {
$("#uploadButton").click(function (event) {
var http = new XMLHttpRequest();
var data = new FormData();
var files = $("#fileSelector").get(0).files;
//data.append(files[0].name, files[0]);
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
http.upload.addEventListener("progress", progressHandler, false);
http.addEventListener("load", completeHandler, false);
http.open("POST", "./Tools/Upload");
http.send(data);
event.preventDefault();
});
});
function progressHandler(event) {
var percent = (event.loaded / event.total) * 100;
$('.bar').width(percent);
}
function completeHandler() {
$('.bar').width(100);
}
Controller 方法是
[HttpPost]
public async Task<ActionResult> Upload(HttpContext context) { ... }
现在,当我单击按钮时,JavaScript 会启动,并且我可以在 data
FormData
对象中看到文件名。但是,我得到了
HTTP/1.1 500 Internal Server Error
当我将方法签名更改为
[HttpPost]
public async Task<ActionResult> Upload(IEnumerable<HttpPostedFileBase> files) { ... }
该方法被调用,但 files
参数为空。
我的 http.send(data);
调用应该使用什么参数类型?
感谢您的宝贵时间。
最佳答案
请使用正确的请求 header 更新您的代码。
http.setRequestHeader("Content-type", "multipart/form-data");
关于javascript - 发送 XMLHttpRequest 未与 Controller 方法绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27619382/