web api 接收文件代码
时间: 2023-09-03 07:15:15 浏览: 40
以下是一个基于ASP.NET的web api接收文件的示例代码:
```
[HttpPost]
public async Task<HttpResponseMessage> UploadFile()
{
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
var file = httpRequest.Files[0];
var fileName = file.FileName;
var filePath = HttpContext.Current.Server.MapPath("~/App_Data/" + fileName);
using (var fileStream = File.Create(filePath))
{
await file.InputStream.CopyToAsync(fileStream);
}
response = Request.CreateResponse(HttpStatusCode.Created);
}
else
{
response = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return response;
}
```
首先,我们使用HttpPost属性将该方法标记为一个HTTP POST请求的处理程序。然后,我们检查请求中是否存在文件并提取第一个文件。接下来,我们创建一个文件路径,将文件保存到该路径并发送一个HTTP响应以指示文件已成功上传。 如果没有文件,则返回一个BadRequest响应。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)