【发布时间】:2019-03-07 20:53:44
【问题描述】:
我正在使用 MVC 5 Web Api 控制器,我希望我的数据通过 ajax 与文件自动绑定?
【问题讨论】:
-
你可以将它附加到formdata。
标签: asp.net-web-api
我正在使用 MVC 5 Web Api 控制器,我希望我的数据通过 ajax 与文件自动绑定?
【问题讨论】:
标签: asp.net-web-api
您可以将上传的文件附加到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!" });
}
【讨论】: