ASP.NET Web Api 2 다 중 파일 을 압축 하고 다운로드 하 는 인 스 턴 스
오늘 점심 시간 을 이용 하여 Asp.Net Web Api 다운로드 파일 에 관 한 글 을 쓰 겠 습 니 다.전에 저도 비슷 한 글 을 쓴 적 이 있 습 니 다.만 나 보 세 요.
본 고 는 이 글 을 바탕 으로 ByteArray Content 의 다운로드 와 여러 파일 을 다운로드 할 때 서버 에서 여러 파일 을 압축 포장 한 후 다운로드 하 는 기능 을 제공 합 니 다.
본 논문 에서 실 현 된 서버 측 에서.NET 압축 으로 파일 을 포장 하 는 기능 에 대해 서 는 여러 번 째 라 이브 러 리 인 DotNetZip 을 사 용 했 습 니 다.구체 적 인 사용 은 본문 에서 언급 될 것 입 니 다.자,이렇게 많은 앞 말 을 묘 사 했 으 니,다음은 본 고의 예시 적 인 본문 으로 들 어가 자.
1.먼저 웹 Api 다운로드 라 는 웹 Api 프로젝트(C\#)를 만 듭 니 다.
2.다음 에 빈 컨트롤 러 를 새로 만 듭 니 다.이름 은 DownloadController 입 니 다.
3.압축 파일 과 임시 파일 을 저장 하 는 폴 더(downloads)를 만 듭 니 다.구체 적 으로 본 논문 에서 마지막 으로 제공 한 예제 항목 코드 를 보십시오.
4.NuGet 프로그램 관리 기 를 열 고 DotNetZip 을 검색 합 니 다.다음 그림:
DotNetZip 설치 패 키 지 를 검색 한 후 이 프로젝트 에서 다 중 파일 압축 기능 을 수행 할 수 있 도록 설치 합 니 다.다음 그림:
DotNetZip 패 키 지 를 설치 하면 NuGet 패키지 관리 자 를 종료 할 수 있 습 니 다.이 프로젝트 는 예시 항목 이기 때문에 다른 패 키 지 를 추가 할 필요 가 없습니다.
5.Models 폴 더 아래 에 예제 데 이 터 를 만 드 는 클래스 입 니 다.이름 은 DemoData 입 니 다.그 중의 구성원 과 실현 은 다음 과 같 습 니 다.
using System.Collections.Generic;
namespace WebApiDownload.Models
{
public class DemoData
{
public static readonly List<List<string>> Contacts = new List<List<string>>();
public static readonly List<string> File1 = new List<string>
{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
};
public static readonly List<string> File2 = new List<string>
{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
};
public static readonly List<string> File3 = new List<string>
{
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
};
public static List<List<string>> GetMultiple
{
get
{
if (Contacts.Count <= 0)
{
Contacts.Add(File1);
Contacts.Add(File2);
Contacts.Add(File3);
}
return Contacts;
}
}
}
}
6.여기까지 우리 의 준비 작업 은 거의 다 르 지 않 습 니 다.마지막 으로 우 리 는 DownloadController 컨트롤 러 에서 두 개의 Action 을 실현 해 야 합 니 다.하 나 는 DownloadSingle(하나의 파일 을 다운로드 하 는 기능 을 제공 합 니 다)이 고 다른 하 나 는 DownloadZip(여러 파일 을 압축 하고 다운로드 하 는 기능 을 제공 합 니 다)입 니 다.구체 적 인 DownloadController 전체 코드 는 다음 과 같 습 니 다.
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using Ionic.Zip;
using WebApiDownload.Models;
using System;
using System.IO;
using System.Net;
using System.Net.Http.Headers;
using System.Threading;
using System.Web;
namespace WebApiDownload.Controllers
{
[RoutePrefix("download")]
public class DownloadController : ApiController
{
[HttpGet, Route("single")]
public HttpResponseMessage DownloadSingle()
{
var response = new HttpResponseMessage();
// List byte[]
var bytes = DemoData.File1.Select(x => x + "
").SelectMany(x => Encoding.UTF8.GetBytes(x)).ToArray();
try
{
var fileName = string.Format("download_single_{0}.txt", DateTime.Now.ToString("yyyyMMddHHmmss"));
var content = new ByteArrayContent(bytes);
response.Content = content;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
}
catch (Exception ex)
{
response.StatusCode = HttpStatusCode.InternalServerError;
response.Content = new StringContent(ex.ToString());
}
return response;
}
[HttpGet, Route("zip")]
public HttpResponseMessage DownloadZip()
{
var response = new HttpResponseMessage();
try
{
var zipFileName = string.Format("download_compressed_{0}.zip", DateTime.Now.ToString("yyyyMMddHHmmss"));
var downloadDir = HttpContext.Current.Server.MapPath($"~/downloads/download");
var archive = $"{downloadDir}/{zipFileName}";
var temp = HttpContext.Current.Server.MapPath("~/downloads/temp");
//
Directory.EnumerateFiles(temp).ToList().ForEach(File.Delete);
ClearDownloadDirectory(downloadDir);
//
var counter = 1;
foreach (var c in DemoData.GetMultiple)
{
var fileName = string.Format("each_file_{0}_{1}.txt", counter, DateTime.Now.ToString("yyyyMMddHHmmss"));
if (c.Count <= 0)
{
continue;
}
var docPath = string.Format("{0}/{1}", temp, fileName);
File.WriteAllLines(docPath, c, Encoding.UTF8);
counter++;
}
Thread.Sleep(500);
using (var zip = new ZipFile())
{
// Make zip file
zip.AddDirectory(temp);
zip.Save(archive);
}
response.Content = new StreamContent(new FileStream(archive, FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = zipFileName };
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
}
catch (Exception ex)
{
response.StatusCode = HttpStatusCode.InternalServerError;
response.Content = new StringContent(ex.ToString());
}
return response;
}
private void ClearDownloadDirectory(string directory)
{
var files = Directory.GetFiles(directory);
foreach (var file in files)
{
try
{
File.Delete(file);
}
catch
{
}
}
}
}
}
이 예제 의 실현 코드 부분 이 완성 되 었 습 니 다.만약 우리 가 이때 주 소 를 열 면:http://localhost:63161/download/single브 라 우 저 는 파일 을 저장 하 는 알림 창 을 팝 업 합 니 다.다음 과 같 습 니 다.이 파일 을 저장 한 후 열 면 예제 데이터 가 로 컬 에 저 장 된 것 을 볼 수 있 습 니 다.다음 과 같 습 니 다.
마찬가지 로 압축 파일 을 다운로드 하려 면 주소:localhost:63161/다운 로드/zip 에 접근 하면 됩 니 다.필 자 는 더 이상 보 여 주지 않 습 니 다.
마지막 으로 본 예시 항목 의 전체 소스 코드 를 동봉 합 니 다ASP.NET(C\#)웹 Api 파일 흐름 을 통 해 파일 을 다운로드 하 는 인 스 턴 스
이상 이 바로 본문의 전체 내용 입 니 다.여러분 께 참고 가 될 수 있 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
부트스트랩 ASP.NET에서 설정하는 법1) _Layout.cshtml 內 link로 bootstrap 참조 2) Nuget 패키지에서 BootStrap 다운로드 3) 하단 부트스트랩 예제 사이트 참고해서 프로젝트 개발 참고 :...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.