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可以處理該請求并將文件保存到服務器。