溫馨提示×

asp.net get請求 能傳遞文件嗎

小樊
120
2024-12-12 19:15:00
欄目: 編程語言

ASP.NET Core Web API 支持通過multipart/form-data格式發送文件和表單數據。要在ASP.NET Core Web API中接收文件,您需要執行以下操作:

  1. 在控制器方法中,使用[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;
    }
}
  1. 在前端HTML中,創建一個包含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可以處理該請求并將文件保存到服務器。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女