ASP.NET Core 上傳檔案示範

在 ASP.NET Core 中要上傳檔案最簡單的方式就是使用 IFormFile
	
[ApiController]
[Route("[controller]")]
public class RuyutController : ControllerBase
{
    private readonly ILogger<RuyutController> _logger;

    public RuyutController(ILogger<RuyutController> logger)
    {
        _logger = logger;
    }

    /// <summary>
    /// 檔案上傳示範
    /// </summary>
    /// <param name="file"></param>
    ///<response code="200">檔案上傳成功</response>
    [ProducesResponseType(typeof(void), 200)]
    [HttpPost]
    public IActionResult Upload(IFormFile file)
    {
        string path = "attachment";
        if (!Directory.Exists(path)) Directory.CreateDirectory(path);

        string filePath = Path.Combine(path, file.FileName);
        try
        {
        	// 上傳檔案
            using Stream fileStream = System.IO.File.Create(filePath);
            file.CopyTo(fileStream);
            fileStream.Close();

            // 取得完整檔案路徑
            string fullPath = Path.GetFullPath(filePath);
            _logger.LogInformation("Upload file success, path: {FilePath}", fullPath);
            return Ok();
        }
        catch (Exception e)
        {
            _logger.LogError(e, "Upload Error");
            return BadRequest();
        }
    }
}
    

上傳測試:



上傳路徑:專案/解決方案/attachment/檔案名稱.副檔名

留言