我如何通过带有Web API模型绑定程序的Ajax使用html输入类型“文件”上传文件

时间:2019-03-07 11:13:24

标签: asp.net-web-api

我正在使用MVC 5 Web Api控制器,我希望通过带有文件的Ajax来自动绑定数据吗?

1 个答案:

答案 0 :(得分:0)

您可以将上传的文件附加到FormData并通过Fetch API发送。


这是一个入门示例:

window.onload = () => {

  document.querySelector('#myFile').addEventListener('change', (event) => {
  
    // Just upload a single file, if you want multiple files then remove the [0]
    if (!event.target.files[0]) {
      alert('Please upload a file');
      return;
    }

    const formData = new FormData();
    formData.append('myFile', event.target.files[0]);

    // Your REST API URL here
    const url = "";

    fetch(url, {
        method: 'post',
        body: formData
      })
      .then(resp => resp.json())
      .then(data => alert('File uploaded successfully!'))
      .catch(err => {
        alert('Error while uploading file!');
      });
  });

};
<input id="myFile" type="file" />

之后,只需使用API​​操作方法从当前请求中获取文件即可。

[HttpPost]
public IHttpActionResult UploadFile()
{
    if (HttpContext.Current.Request.Files.Count > 0)
    {
        var file = HttpContext.Current.Request.Files[0];

        if (file != null)
        {
            // Do something with file now
        }
    }

    return Ok(new { message = "File uploaded successfully!" }); 
}