ASP.NET Core Web API 파일 업로드 및 다운로드
추천 자료: ASP.NET Core 인증 및 권한 부여
ASP.NET Core Web API 프로젝트에서 wwwroot/tempfiles
폴더로 파일을 업로드하고, 해당 폴더에서 특정 파일을 다운로드하는 API를 작성하고 테스트하는 전체 절차입니다.
1. 프로젝트 생성
ASP.NET Core Web API 프로젝트 생성
dotnet new webapi -n DotNetNote cd DotNetNote
필요한 패키지 설치
낮은 버전의 ASP.NET Core에서는 다음 패키지 설치가 필요한데요. 최신 버전을 사용하면, ASP.NET Core에 이미 이 기능이 포함되어서 다음 패키지를 추가로 설치할 필요가 없습니다.
dotnet add package Microsoft.AspNetCore.StaticFiles
- 프로젝트 실행
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으로 업로드 테스트
- URL:
http://localhost:5000/api/webapifileuploaddownloadtest/upload
- Method: POST
- Body:
form-data
를 선택Key
:file
(드롭다운에서File
선택)- 파일 선택하여 업로드
- 응답 확인: 업로드된 파일 이름과 경로가 반환됩니다.
3) POSTMAN으로 다운로드 테스트
- URL:
http://localhost:5000/api/webapifileuploaddownloadtest/download/{fileName}
- Method: GET
- 응답: 파일이 다운로드됩니다.
5. 테스트 폴더 확인
- 업로드된 파일은 프로젝트의
wwwroot/tempfiles
폴더에 저장됩니다. - 다운로드 시 해당 경로에서 파일을 가져옵니다.
추천 자료: .NET Blazor에 대해 알아보시겠어요? .NET Blazor 알아보기를 확인해보세요!