ASP.NET Core Web API 파일 업로드 및 다운로드

  • 2 minutes to read

ASP.NET Core Web API 프로젝트에서 wwwroot/tempfiles 폴더로 파일을 업로드하고, 해당 폴더에서 특정 파일을 다운로드하는 API를 작성하고 테스트하는 전체 절차입니다.

1. 프로젝트 생성

  1. ASP.NET Core Web API 프로젝트 생성

    dotnet new webapi -n DotNetNote
    cd DotNetNote
    
  2. 필요한 패키지 설치

낮은 버전의 ASP.NET Core에서는 다음 패키지 설치가 필요한데요. 최신 버전을 사용하면, ASP.NET Core에 이미 이 기능이 포함되어서 다음 패키지를 추가로 설치할 필요가 없습니다.

dotnet add package Microsoft.AspNetCore.StaticFiles
  1. 프로젝트 실행
    dotnet run
    

2. 파일 업로드 및 다운로드 API 작성

Controllers/WebApiFileUploadDownloadTestController.cs 작성

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using System.IO;
using System.Threading.Tasks;

namespace DotNetNote.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class WebApiFileUploadDownloadTestController : ControllerBase
    {
        private readonly string _tempFilesPath;

        public WebApiFileUploadDownloadTestController()
        {
            _tempFilesPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "tempfiles");

            // Ensure the directory exists
            if (!Directory.Exists(_tempFilesPath))
            {
                Directory.CreateDirectory(_tempFilesPath);
            }
        }

        // 파일 업로드
        [HttpPost("upload")]
        public async Task<IActionResult> UploadFile(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return BadRequest("No file uploaded");

            var filePath = Path.Combine(_tempFilesPath, file.FileName);

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            return Ok(new { FileName = file.FileName, FilePath = filePath });
        }

        // 파일 다운로드
        [HttpGet("download/{fileName}")]
        public IActionResult DownloadFile(string fileName)
        {
            var filePath = Path.Combine(_tempFilesPath, fileName);

            if (!System.IO.File.Exists(filePath))
                return NotFound("File not found");

            var provider = new FileExtensionContentTypeProvider();
            if (!provider.TryGetContentType(filePath, out var contentType))
            {
                contentType = "application/octet-stream";
            }

            var fileBytes = System.IO.File.ReadAllBytes(filePath);
            return File(fileBytes, contentType, fileName);
        }
    }
}

3. Startup 설정

Program.cs 수정

ASP.NET Core 7 이상에서는 Program.cs에 파일 제공을 설정해야 합니다.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// Static files middleware 설정
app.UseStaticFiles();

app.UseRouting();

app.MapControllers();

app.Run();

4. 테스트

1) 프로젝트 실행

dotnet run

2) POSTMAN으로 업로드 테스트

  1. URL: http://localhost:5000/api/webapifileuploaddownloadtest/upload
  2. Method: POST
  3. Body:
    • form-data를 선택
    • Key: file (드롭다운에서 File 선택)
    • 파일 선택하여 업로드
  4. 응답 확인: 업로드된 파일 이름과 경로가 반환됩니다.

3) POSTMAN으로 다운로드 테스트

  1. URL: http://localhost:5000/api/webapifileuploaddownloadtest/download/{fileName}
  2. Method: GET
  3. 응답: 파일이 다운로드됩니다.

5. 테스트 폴더 확인

  • 업로드된 파일은 프로젝트의 wwwroot/tempfiles 폴더에 저장됩니다.
  • 다운로드 시 해당 경로에서 파일을 가져옵니다.
VisualAcademy Docs의 모든 콘텐츠, 이미지, 동영상의 저작권은 박용준에게 있습니다. 저작권법에 의해 보호를 받는 저작물이므로 무단 전재와 복제를 금합니다. 사이트의 콘텐츠를 복제하여 블로그, 웹사이트 등에 게시할 수 없습니다. 단, 링크와 SNS 공유, Youtube 동영상 공유는 허용합니다. www.VisualAcademy.com
박용준 강사의 모든 동영상 강의는 데브렉에서 독점으로 제공됩니다. www.devlec.com