ASP.NET Web Api 2 다 중 파일 을 압축 하고 다운로드 하 는 인 스 턴 스

최근 에 업무 와 개인 업무 로 인해 사이트 도 오랫동안 업데이트 되 지 않 았 지만 이것 은 내 가.NET 에 대한 열정 에 영향 을 주지 않 았 다.사이트 의 업 데 이 트 는 시간 을 내 서 완성 해 야 한다.
오늘 점심 시간 을 이용 하여 Asp.Net Web Api 다운로드 파일 에 관 한 글 을 쓰 겠 습 니 다.전에 저도 비슷 한 글 을 쓴 적 이 있 습 니 다.만 나 보 세 요.
본 고 는 이 글 을 바탕 으로 ByteArray Content 의 다운로드 와 여러 파일 을 다운로드 할 때 서버 에서 여러 파일 을 압축 포장 한 후 다운로드 하 는 기능 을 제공 합 니 다.
본 논문 에서 실 현 된 서버 측 에서.NET 압축 으로 파일 을 포장 하 는 기능 에 대해 서 는 여러 번 째 라 이브 러 리 인 DotNetZip 을 사 용 했 습 니 다.구체 적 인 사용 은 본문 에서 언급 될 것 입 니 다.자,이렇게 많은 앞 말 을 묘 사 했 으 니,다음은 본 고의 예시 적 인 본문 으로 들 어가 자.
1.먼저 웹 Api 다운로드 라 는 웹 Api 프로젝트(C\#)를 만 듭 니 다.
2.다음 에 빈 컨트롤 러 를 새로 만 듭 니 다.이름 은 DownloadController 입 니 다.
3.압축 파일 과 임시 파일 을 저장 하 는 폴 더(downloads)를 만 듭 니 다.구체 적 으로 본 논문 에서 마지막 으로 제공 한 예제 항목 코드 를 보십시오.
4.NuGet 프로그램 관리 기 를 열 고 DotNetZip 을 검색 합 니 다.다음 그림:
//img.jbzj.com/file_images/article/201606/2016062309583710.png
DotNetZip 설치 패 키 지 를 검색 한 후 이 프로젝트 에서 다 중 파일 압축 기능 을 수행 할 수 있 도록 설치 합 니 다.다음 그림:
//img.jbzj.com/file_images/article/201606/2016062309583711.png
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브 라 우 저 는 파일 을 저장 하 는 알림 창 을 팝 업 합 니 다.다음 과 같 습 니 다.
//img.jbzj.com/file_images/article/201606/2016062309583714.png
이 파일 을 저장 한 후 열 면 예제 데이터 가 로 컬 에 저 장 된 것 을 볼 수 있 습 니 다.다음 과 같 습 니 다.
//img.jbzj.com/file_images/article/201606/2016062309583815.png
마찬가지 로 압축 파일 을 다운로드 하려 면 주소:localhost:63161/다운 로드/zip 에 접근 하면 됩 니 다.필 자 는 더 이상 보 여 주지 않 습 니 다.
마지막 으로 본 예시 항목 의 전체 소스 코드 를 동봉 합 니 다ASP.NET(C\#)웹 Api 파일 흐름 을 통 해 파일 을 다운로드 하 는 인 스 턴 스
이상 이 바로 본문의 전체 내용 입 니 다.여러분 께 참고 가 될 수 있 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.

좋은 웹페이지 즐겨찾기