ASP.NET Core Web API 支持通过multipart/form-data格式发送文件和表单数据。要在ASP.NET Core Web API中接收文件,您需要执行以下操作:
[FromForm]
属性指定接收文件的参数。例如:using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class UploadController : ControllerBase
{
[HttpPost]
public async Task<IActionResult> Post([FromForm] IFormFile file)
{
if (file == null || file.Length == 0)
{
return BadRequest("No file uploaded.");
}
// 处理文件,例如保存到服务器
return CreatedAtAction(nameof(Get), new { id = file.FileName }, file);
}
[HttpGet("{filename}")]
public async Task<IActionResult> Get(string filename)
{
// 从服务器检索文件并返回
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", filename);
var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
var fileContent = new StreamContent(fileStream);
var response = new ResponseContentResult(fileContent)
{
ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = filename
}
};
return response;
}
}
enctype="multipart/form-data"
属性的<form>
元素,并使用FormData
对象添加文件。例如:<!DOCTYPE html>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form action="/api/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>
</body>
</html>
这样,当用户选择一个文件并提交表单时,文件将作为multipart/form-data请求的一部分发送到ASP.NET Core Web API。API可以处理该请求并将文件保存到服务器。