简体   繁体   English

异步将文件上传到MVC.NET

[英]Upload a file asynchronously to MVC.NET

I want to upload a file asynchronously from a web page to an ASP.NET MVC action: 我想从网页异步上传文件到ASP.NET MVC操作:

[HttpPost]
public JsonResult AnalyseFile(HttpPostedFileBase file)
{
  // do stuff
  return Json(someResultObjects);
}

My problem is that when the method executes on the server, the file argument is null. 我的问题是,当该方法在服务器上执行时,file参数为null。

Over in HTML land, I have an input field containing a file: 在HTML领域中,我有一个包含文件的输入字段:

<input type="file" accept=".xlsx" required="required" id="FileInput" name="FileInput" onchange="javascript:AnalyseFile();" />

And I have some javascript code: 而且我有一些JavaScript代码:

function AnalyseFile() {
  var fileInput = document.getElementById('FileInput');
  var file = fileInput.files[0];
  var url = 'http://someserver/somecontroller/AnalyseFile';
  var xhr = new XMLHttpRequest();
  xhr.upload.onreadystatechange = function() {
    if(xhr.readyState == 4) {
      // do stuff
    }
  };
  xhr.open('POST', url, true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.send('file=' + file);
}

I've verified that the javascript file object has a reference to the file by inserting the following line of code after var file = fileInput.files[0]: 我已通过在var file = fileInput.files [0]之后插入以下代码行来验证javascript文件对象对文件的引用:

alert(file.Name);

which correctly displays the file name in a message box. 在消息框中正确显示文件名。

However, when the server side method is called, the file itself is missing (the HttpPostedFileBase "file" argument is null). 但是,在调用服务器端方法时,文件本身丢失了(HttpPostedFileBase“ file”参数为null)。 Can anyone advise me what I'm doing wrong here? 有人可以告诉我我在做什么错吗? The objective is for the HttpPostedFileBase to have the reference to the file so I can do some analyses on it on the server and send the results back to the browser for rendering to the user. 目的是让HttpPostedFileBase拥有对该文件的引用,因此我可以在服务器上对此文件进行一些分析,然后将结果发送回浏览器以呈现给用户。

You can allow Mediatype headers to accept 'application/x-www-form-urlencoded' in server side . 您可以允许Mediatype标头服务器端 接受'application / x-www-form-urlencoded' The default formatter might not support 'application/x-www-form-urlencoded' , Hence file is null . 默认格式化程序可能不支持'application / x-www-form-urlencoded',因此文件为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM