asp.net Web Api 2 Implementation multi-file packaging and download the file instance _ practical Tips

Source: Internet
Author: User
Tags datetime make zip file httpcontext

Recently because of work and personal affairs, the site has not been updated for a long time, but this does not affect my right. Net of enthusiasm. Site update work still have to find a way to make time to complete.

Today I use the noon time to write an article about the asp.net Web api download file, before I have written a similar article, see: "ASP.net (C #) Web API streaming files through file instances"

This article, based on this article, provides bytearraycontent downloads and the ability to download multiple files when the server is compressed and packaged.

about what is implemented in this article on the server side. NET Compression package file function, the use of a DotNetZip library: the specific use of the text will be involved in the body. Well, with so many preface, let's go to the body of the example below.

1. First create a Web Api project named: Webapidownload (C #);

2. Then create a new empty controller, named: Downloadcontroller;

3. Create some packaged files and temporary files folder (downloads), specifically, see the sample project code provided at the end of this article

4. Open the NuGet package steward, search DotNetZip, the following figure:

After the dotnetzip installation package is searched, it is installed for use in this project to achieve the function of multiple file packaging compression, as shown below:

After the DotNetZip package has been installed, we can exit NuGet Package Manager because this project is a sample project and no additional packages are required.

5. Create a class of sample data under the Models folder, named: Demodata, where the members and implementations are as follows:

Using System.Collections.Generic; Namespace Webapidownload.models {public class Demodata {public static readonly list<list<string>> Contac
  ts = new list<list<string>> (); public static readonly list<string> File1 = new List<string> {"f_1_test_1@example.com", "f_1_test_2@e
  Xample.com "," f_1_test_3@example.com "," f_1_test_4@example.com "," f_1_test_5@example.com "}; public static readonly list<string> File2 = new List<string> {"f_2_test_1@example.com", "f_2_test_2@e
  Xample.com "," f_2_test_3@example.com "," f_2_test_4@example.com "," f_2_test_5@example.com "}; public static readonly list<string> File3 = new List<string> {"f_3_test_1@example.com", "f_3_test_2@e

  Xample.com "," f_3_test_3@example.com "," f_3_test_4@example.com "," f_3_test_5@example.com "};
public static list<list<string>> GetMultiple {get {if (contacts.count <= 0) {     Contacts.add (FILE1);
     Contacts.add (File2);
    Contacts.add (FILE3);
   return Contacts;

 }
  }
 }
}

6. Here, our preparations are almost done, and finally we only need to implement two action in the Downloadcontroller controller, one for: Downloadsingle (to provide the ability to download a single file), The other is: Downloadzip (provides the ability to pack and compress multiple files and download them). the exact Downloadcontroller complete code is as follows:

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 {[H
   Ttpget, Route (' single ')] public httpresponsemessage downloadsingle () {var response = new Httpresponsemessage (); Gets byte[] var bytes = DemoData.File1.Select (x => x + "\ n") from the list collection. 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"); The 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"); Clears all temporary files Directory.enumeratefiles (temp) in the temporary folder. ToList ().
    ForEach (File.delete);
    Cleardownloaddirectory (Downloaddir);
    Generate a new temporary file 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"); The 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 {}}}}

In this case, the implementation code section of this example is complete, and if we open the address at this point: Http://localhost:63161/download/single, the browser pops up the prompt to save the file, as follows:

After saving this file, open it and we'll see that our sample data has been saved locally, as follows:

Similarly, download the compressed file you only need to access the address: Localhost:63161/download/zip can, the author will no longer demonstrate.

Finally, attach the complete source code of this sample project, click here to download.

The above is the entire content of this article, I hope to give you a reference, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.