관리 메뉴

웹개발자의 기지개

[ASP.Net Core] 대용량 파일 업로드 시키기 본문

ASP.NET/ASP.NET Core

[ASP.Net Core] 대용량 파일 업로드 시키기

http://portfolio.wonpaper.net 2024. 3. 8. 04:02

최대 1GB 의 대용량 파일 업로드를 시키는 방법을 고안해 보았다.

 

 

https://github.com/wonpaper/BigFileUpload

 

GitHub - wonpaper/BigFileUpload: ASP.Net Core6 으로 만든 대용량 파일업로드 샘플

ASP.Net Core6 으로 만든 대용량 파일업로드 샘플. Contribute to wonpaper/BigFileUpload development by creating an account on GitHub.

github.com

 

 

[ Program.cs ]

 

1
2
3
4
5
6
7
8
9
10
11
12
using Microsoft.AspNetCore.Http.Features;
 
....
 
// 전역으로 최대업로드 용량 설정
builder.WebHost.ConfigureKestrel(options => {
    options.Limits.MaxRequestBodySize = 1024 * 1024 * 1024// 1GB
});
 
builder.Services.Configure<FormOptions>(options => {
    options.MultipartBodyLengthLimit = 1024 * 1024 * 1024// 1GB
});
cs

 

Global 하게 설정해 놓았다.

 

위에서 대용량 파일 처리중에 제일 중요한 부분이

using Microsoft.AspNetCore.Http.Features;

요놈이다. 임포트해서 FormOptions 객체를 이용해서 쓴다.

 

 

 

[ HomeController.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 BigFileUpload.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Net.Http.Headers;
 
namespace BigFileUpload.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private IWebHostEnvironment environment;
 
        public HomeController(ILogger<HomeController> logger, IWebHostEnvironment environment)
        {
            _logger = logger;
            this.environment = environment;
        }
       
 
        public IActionResult Index()
        {
            return View();
        }
 
        [HttpPost]
        //[RequestSizeLimit(1024 * 1024 * 1024)]
        public async Task<IActionResult> Index(ICollection<IFormFile> file1)
        {
            var uploadFolder = String.Empty;
            string fileName1 = String.Empty;
            int fileSize1 = 0;
 
            uploadFolder = Path.Combine(environment.WebRootPath, "files/Notice");
            foreach (var file in file1)
            {
                if (file.Length > 0)
                {
                    fileSize1 = Convert.ToInt32(file.Length);
                    // 파일명 중복 처리
                    fileName1 = Dul.FileUtility.GetFileNameWithNumbering(
                        uploadFolder, Path.GetFileName(ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"')));
                    // 파일 업로드
                    using (var fileStream = new FileStream(
                        Path.Combine(uploadFolder, fileName1), FileMode.Create))
                    {
                        await file.CopyToAsync(fileStream);
                    }
                }
            }
 
            return View(file1);
        }
 
        public IActionResult Privacy()
        {
            return View();
        }
 
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
 
cs

 

26 라인의 주석으로 막아 놓은부분은 Global 하게 설정해 놓았기 때문에 쓸 필요가 없다.

 

[ Index.cshtml ]

 

 

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
@model ICollection<IFormFile>
@{
    ViewData["Title"= "Home Page";
 
    string FormatFileSize(long fileSizeInBytes)
    {
        const int byteConversion = 1024;
        double bytes = Convert.ToDouble(fileSizeInBytes);
 
        if (fileSizeInBytes >= Math.Pow(byteConversion, 3)) // Size is greater than or equal to 1 GB
        {
            return $"{bytes / Math.Pow(byteConversion, 3):0.##} GB";
        }
        else if (fileSizeInBytes >= Math.Pow(byteConversion, 2)) // Size is greater than or equal to 1 MB
        {
            return $"{bytes / Math.Pow(byteConversion, 2):0.##} MB";
        }
        else if (fileSizeInBytes >= byteConversion) // Size is greater than or equal to 1 KB
        {
            return $"{bytes / byteConversion:0.##} KB";
        }
        else // Size is less than 1 KB
        {
            return $"{bytes} bytes";
        }
    }
}
 
<div class="text-center">
    <h1 class="display-4">대용량 파일 업로드 (최대 1GB까지)</h1>
    
    <form name="f" method="post" enctype="multipart/form-data">
 
        <div class="form-group">
 
            <div>
                <input type="file" name="file1" class="form-control">
            </div>
 
            <div class="mt-3">
                <button class="btn btn-primary" type="submit">Send</button>
            </div>
 
            @if (Model != null)
            {
                <div class="mt-3">
                    파일명: @Model.ElementAt(0).FileName
                    <br />
                    파일크기: @FormatFileSize(Model.ElementAt(0).Length)
                 </div>
            }
        </div>
    </form>
</div>
 
cs

 

 

 

 

 

참고 : https://www.youtube.com/watch?v=ollScUHiFKs

 

 

 

추가로 아래의 유투브 내용도 시간도 짧고 아주 괜찮았다.

https://www.youtube.com/watch?v=SqhqLDrzzaM

 

Comments