31.4.2 따라하기

    1. DotNetNote 프로젝트에서 FileDemoController.cs 파일로 컨트롤러를 생성하고 다음과 같이 코드를 작성한다. 생성자에 IHostingEnvironment 인터페이스를 매개 변수로 전달 받아 웹 프로젝트의 wwwroot 폴더에 대한 물리적인 경로를 받을 수 있도록 설정하자. FileUploadDemo 액션 메서드를 하나 만들고, 이에 대한 HttpGetHttpPost 메서드를 구분한다. 전체 소스는 다음과 같다.

    ▼  Controllers/FileDemoController.cs

    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Net.Http.Headers;
    using System.Collections.Generic;
    using System.IO;
    using System.Threading.Tasks;
    
    namespace DotNetNote.Controllers
    {
      public class FileDemoController : Controller
      {
          private IHostingEnvironment _environment;
          
          public FileDemoController(IHostingEnvironment environment)
          {
              _environment = environment;
          }
          
          /// <summary>
          /// 파일 업로드 폼 
          /// </summary>
            [HttpGet]
          public IActionResult FileUploadDemo()
          {
              return View();
          }
          
          /// <summary>
          /// 파일 업로드 처리
          /// </summary>
            [HttpPost]
          public async Task<IActionResult> FileUploadDemo(
              ICollection<IFormFile> files)
          {
              var uploadFolder = Path.Combine(_environment.WebRootPath, “files”);
              
              foreach (var file in files)
              {
                  if (file.Length > 0)
                  {
                      var fileName = Path.GetFileName(
                          ContentDispositionHeaderValue.Parse(
                              file.ContentDisposition).FileName.Trim(’“’));
                      
                      using (var fileStream = new FileStream(
                          Path.Combine(uploadFolder, fileName), FileMode.Create))
                      {
                          await file.CopyToAsync(fileStream);
                      }
                  }
              }
              
              return View();
          }
          
          /// <summary>
          /// 파일 다운로드 처리 데모
          /// </summary>
          public FileResult FileDownloadDemo(string fileName = “Test.txt”)
          {
              byte[] fileBytes = System.IO.File.ReadAllBytes(
                  Path.Combine(
                      _environment.WebRootPath, “files”) + “\“ + fileName);
              
              return File(fileBytes, “application/octet-stream”, fileName);
          }
      }
    }
    

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.