【问题标题】:How I can upload a file using html input type "file" through ajax with web API model binder如何通过带有 Web API 模型绑定器的 ajax 使用 html 输入类型“文件”上传文件
【发布时间】:2019-03-07 20:53:44
【问题描述】:

我正在使用 MVC 5 Web Api 控制器,我希望我的数据通过 ajax 与文件自动绑定?

【问题讨论】:

  • 你可以将它附加到formdata。

标签: asp.net-web-api


【解决方案1】:

您可以将上传的文件附加到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!" }); 
}

【讨论】:

    猜你喜欢
    • 2016-10-06
    • 2016-07-02
    • 1970-01-01
    • 2010-12-30
    • 2013-10-21
    • 2021-12-28
    • 2011-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多