반응형
Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
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
Tags
more
Archives
Today
Total
관리 메뉴

개발꿈나무

[Blazor] server에 있는 파일 다운로드 받기 - BlazorDownloadFile 본문

C#/Blazor

[Blazor] server에 있는 파일 다운로드 받기 - BlazorDownloadFile

HYOKYE0NG 2021. 10. 22. 11:06
반응형

server에 있는 파일을 다운로드 받으려면 보통 request/response를 사용한다.

하지만 blazor에서는 request/response 객체가 없기 때문에

꽤나 복잡하게 구현해야 한다.(물론 내 기준)

 

아무튼 그래서 나는 BlazorDownloadFile이라는 패키지를 이용했다.

 

GitHub - arivera12/BlazorDownloadFile: Blazor download files to the browser from c# without any javascript library reference or

Blazor download files to the browser from c# without any javascript library reference or dependency. - GitHub - arivera12/BlazorDownloadFile: Blazor download files to the browser from c# without an...

github.com

 

 

NuGet 설치 방법은 아래의 포스팅에 설명되어 있다.

 

[Blazor] NuGet Package 설치하기

프로젝트를 하면서 nuget 패키지를 설치해야 할 경우가 종종 있다. 다양한 기능들을 지원해주는 nuget package 어떻게 설치하고 사용하는지 알아보자 우선, 이번에 내가 설치할 nuget은 BlazorDownloadFile

hyokye0ng.tistory.com

 

 

NuGet을 설치했다고 가정한 후 사용방법을 알아보자.

 

BlazorDownloadFile의 기능을 사용하기 전에 @using과 @inject로 선언해주어야 한다.

물론@using문은 _Import.razor파일에 입력해도 무방하다.

@using BlazorDownloadFile
@inject IBlazorDownloadFileService BlazorDownloadFileService

 

이제 BlazorDownloadFile의 메소드를 사용해서 파일을 다운받으면 되는데,

아래의 사진과 같이 DownloadFile이라는 메소드가 아주 많이 오버로드 되어있다.

속성은 대부분 비슷하며 조합이 다른 경우가 많은 것 같다.

이 중 내가 생소했던 속성들만 살펴보자면

contentType: MIME Type이라고도 하는데 MIME은 "Multipurpose Internet Mail Extensions"의 약자로

파일 변환을 위한 포맷이다. 일반적으로 '타입/서브타입' 형태로 구성된다.

CacellationToken: 비동기 작업을 취소시키는 작업을 수행한다.

 

나는 이 중 DownloadFile(string fileName, byte[] bytes, string contentType) 메소드를 사용했다.

string xml_path = @"C:\Users\Desktop\test.xml";
byte[] filebytes = File.ReadAllBytes(xml_path);
BlazorDownloadFileService.DownloadFile("test", filebytes, "text/xml");

 

xml file을 다운받는 메소드 전체 소스코드는 다음과 같다.

private void XML_Download(string dcn_no)
    {
        string xmlrepositoryString = SysinfoService.GetXMLRepository();
        string xml_path = @$"{xmlrepositoryString}\{dcn_no}.xml";

        if (File.Exists(xml_path))
        {
            byte[] filebytes = File.ReadAllBytes(xml_path);

            try
            {
                BlazorDownloadFileService.DownloadFile(dcn_no, filebytes, "text/xml");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }

 

반응형
Comments