■ 스트림을 사용해 대용량 파일을 업로드하는 방법을 보여준다.
[TestServer 프로젝트]
▶ launchSettings.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
{ "$schema" : "http://json.schemastore.org/launchsettings.json", "iisSettings" : { "windowsAuthentication" : false, "anonymousAuthentication" : true, "iisExpress" : { "applicationUrl" : "http://localhost:41483", "sslPort" : 44362 } }, "profiles" : { "IIS Express" : { "commandName" : "IISExpress", "launchBrowser" : true, "launchUrl" : "swagger", "environmentVariables" : { "ASPNETCORE_ENVIRONMENT" : "Development" } }, "TestServer" : { "commandName" : "Project", "dotnetRunMessages" : "true", "launchBrowser" : true, "launchUrl" : "swagger", "applicationUrl" : "https://localhost:5001;http://localhost:5000", "environmentVariables" : { "ASPNETCORE_ENVIRONMENT" : "Development" } } } } |
▶ appsettings.json
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
{ "Logging" : { "LogLevel" : { "Default" : "Information", "Microsoft" : "Warning", "Microsoft.Hosting.Lifetime" : "Information" } }, "AllowedHosts" : "*", "APIKey" : "A7A54AD3-91E1-4C3A-98C6-A17E39C9EA3D" } |
▶ web.config
1 2 3 4 5 6 7 8 9 10 11 12 |
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="2147483648" /> </requestFiltering> </security> </system.webServer> </configuration> |
※ IIS Express 사용시 참조된다.
▶ APIKeyAttribute.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using System.Threading.Tasks; namespace TestServer { /// <summary> /// API 키 어트리뷰트 /// </summary> [AttributeUsage(validOn: AttributeTargets.Class)] public class APIKeyAttribute : Attribute, IAsyncActionFilter { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// API 키명 /// </summary> public static readonly string API_KEY_NAME = "APIKey"; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 액션 실행시 처리하기 (비동기) - OnActionExecutionAsync(context, nextAction) /// <summary> /// 액션 실행시 처리하기 (비동기) /// </summary> /// <param name="context">액션 실행 컨텍스트</param> /// <param name="nextAction">다음 액션 실행 대리자</param> /// <returns>태스크</returns> public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate nextAction) { if(!context.HttpContext.Request.Headers.TryGetValue(API_KEY_NAME, out var sourceAPIKey)) { context.Result = new ContentResult() { StatusCode = 401, Content = "API Key was not provided." }; return; } IConfiguration configuration = context.HttpContext.RequestServices.GetRequiredService<IConfiguration>(); string targetAPIKey = configuration.GetValue<string>(API_KEY_NAME); if(!targetAPIKey.Equals(sourceAPIKey)) { context.Result = new ContentResult() { StatusCode = 401, Content = "API Key is not valid." }; return; } await nextAction(); } #endregion } } |
▶ FileController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
using Microsoft.AspNetCore.Mvc; using System.IO; using System.Threading.Tasks; namespace TestServer.Controllers { /// <summary> /// 파일 컨트롤러 /// </summary> [Route("api/[controller]/[action]")] [ApiController] [APIKey] public class FileController : ControllerBase { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 최대 파일 크기 /// </summary> private const long MAXIMUM_FILE_SIZE = 10737418240L; // 10GB #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 업로드하기 - Upload() /// <summary> /// 업로드하기 /// </summary> /// <returns>액션 결과 태스크</returns> [HttpPost] [RequestSizeLimit(MAXIMUM_FILE_SIZE)] [RequestFormLimits(MultipartBodyLengthLimit = MAXIMUM_FILE_SIZE)] public async Task<IActionResult> Upload() { using(Stream sourceStream = Request.Body) { string fileName = Request.Headers["FileName"]; string targetFilePath = Path.Combine("d:\\Download", fileName); if(!System.IO.File.Exists(targetFilePath)) { using(FileStream targetStream = new FileStream(targetFilePath, FileMode.Create)) { await sourceStream.CopyToAsync(targetStream); } return new JsonResult(new { FilePath = targetFilePath }); } // 파일이 존재하는 경우 잘못된 요청을 반환한다. return BadRequest(); } } #endregion } } |
▶ Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 |
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; namespace TestServer { /// <summary> /// 시작 /// </summary> public class Startup { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 구성 - Configuration /// <summary> /// 구성 /// </summary> public IConfiguration Configuration { get; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - Startup(configuration) /// <summary> /// 생성자 /// </summary> /// <param name="configuration">구성</param> public Startup(IConfiguration configuration) { Configuration = configuration; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서비스 컬렉션 구성하기 - ConfigureServices(serviceCollection) /// <summary> /// 서비스 컬렉션 구성하기 /// </summary> /// <param name="serviceCollection">서비스 컬렉션</param> public void ConfigureServices(IServiceCollection serviceCollection) { serviceCollection.AddControllers(); serviceCollection.AddSwaggerGen ( options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "TestServer", Version = "v1" }); } ); serviceCollection.Configure<FormOptions> ( options => { options.MultipartBodyLengthLimit = 10737418240L; // 10GB } ); } #endregion #region 구성하기 - Configure(applicationBuilder, webHostEnvironment) /// <summary> /// 구성하기 /// </summary> /// <param name="applicationBuilder">애플리케이션 빌더</param> /// <param name="webHostEnvironment">웹 호스트 환경</param> public void Configure(IApplicationBuilder applicationBuilder, IWebHostEnvironment webHostEnvironment) { if(webHostEnvironment.IsDevelopment()) { applicationBuilder.UseDeveloperExceptionPage(); applicationBuilder.UseSwagger(); applicationBuilder.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "TestServer v1")); } applicationBuilder.UseHttpsRedirection(); applicationBuilder.UseRouting(); applicationBuilder.UseAuthorization(); applicationBuilder.UseEndpoints ( endpointRouteBuilder => { endpointRouteBuilder.MapControllers(); } ); } #endregion } } |
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace TestServer { /// <summary> /// 프로그램 /// </summary> public class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 호스트 빌더 생성하기 - CreateHostBuilder(argumentList) /// <summary> /// 호스트 빌더 생성하기 /// </summary> /// <param name="argumentList">인자 리스트</param> /// <returns>호스트 빌더</returns> public static IHostBuilder CreateHostBuilder(string[] argumentList) => Host.CreateDefaultBuilder(argumentList) .ConfigureWebHostDefaults ( webBuilder => { webBuilder.UseStartup<Startup>(); webBuilder.UseKestrel ( options => { options.Limits.MaxRequestBodySize = 10737418240L; // 10GB } ); } ); #endregion #region 프로그램 시작하기 - Main(argumentList) /// <summary> /// 프로그램 시작하기 /// </summary> /// <param name="argumentList">인자 리스트</param> public static void Main(string[] argumentList) { CreateHostBuilder(argumentList).Build().Run(); } #endregion } } |
[TestClient 프로젝트]
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace TestClient { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region HTTP 클라이언트 구하기 - GetHTTPClient(baseAddress) /// <summary> /// HTTP 클라이언트 구하기 /// </summary> /// <param name="baseAddress">기준 주소</param> /// <returns>HTTP 클라이언트</returns> private static HttpClient GetHTTPClient(string baseAddress) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(baseAddress); client.DefaultRequestHeaders.Add("APIKey", "A7A54AD3-91E1-4C3A-98C6-A17E39C9EA3D"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return client; } #endregion #region 파일 업로드하기 (비동기) - UploadFileAsync(client, filePath) /// <summary> /// 파일 업로드하기 (비동기) /// </summary> /// <param name="client">클라이언트</param> /// <param name="filePath">파일 경로</param> /// <returns>HTTP 응답 메시지 태스크</returns> private static async Task<HttpResponseMessage> UploadFileAsync(HttpClient client, string filePath) { string url = string.Format("/api/File/Upload"); client.DefaultRequestHeaders.Add("FileName", Path.GetFileName(filePath)); using(FileStream sourceStream = new FileStream(filePath, FileMode.Open)) { StreamContent content = new StreamContent(sourceStream); HttpResponseMessage httpResponseMessage = await client.PostAsync(url, content); return httpResponseMessage; } } #endregion #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> static void Main() { Console.WriteLine("아무 키나 눌러 주시기 바랍니다."); Console.WriteLine("--------------------------------------------------"); Console.ReadKey(true); //using(HttpClient client = GetHTTPClient("https://localhost:44362")) // IIE Express 사용시 using(HttpClient client = GetHTTPClient("https://localhost:5001")) { // 파일 크기는 2GB까지만 가능하다. var response = UploadFileAsync(client, @"d:\sample.mp4").GetAwaiter().GetResult(); Console.WriteLine(response.StatusCode); Console.WriteLine(response.ReasonPhrase); } Console.WriteLine("--------------------------------------------------"); Console.WriteLine("아무 키나 눌러 주시기 바랍니다."); Console.ReadKey(true); } #endregion } } |