ASP. NET Web Api 2 implements multi-file package and download file Sample source _

Source: Internet
Author: User
Tags make zip file



An article about the ASP. NET Web API download file, I've written a similar article before, see: The ASP. NET (C #) Web API downloads files to an on-premises instance via a file stream
Based on this article, this paper provides the download of bytearraycontent and the ability to download multiple files when the server is compressed and packaged.
About the server-side implementations that are implemented in this article. NET compress the package file function, used to a class library: DotNetZip, the specific use will be covered in the body. Well, describing so many preface, let's go into the body of the sample in this article.


First, create the project


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



1.2 Then create a new empty controller, named: Downloadcontroller;



1.3 Create some packaged files and folders to hold temporary files (downloads), see the sample project code provided at the end of this article



1.4 Open the NuGet package steward and search for DotNetZip, such as:




After you have searched for the DotNetZip installation package, install it for use in this project to implement multi-file packaging compression features, such as:



After the DotNetZip package is installed, we can exit the NuGet Package Manager because this project is a sample project and no additional packages need to be added.



1.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>> 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;
            }
        }
    }
}
}
View Code


1.6 Here, we basically do the preparatory work almost, and finally we only need to implement two actions in the Downloadcontroller controller, one is: Downloadsingle (provides the ability to download a single file), The other is: Downloadzip (provides the ability to package and compress multiple files and download them). The specific 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
    {
        [HttpGet, Route ("single")]
        public HttpResponseMessage DownloadSingle ()
        {
            var response = new HttpResponseMessage ();
            // Get byte [] from the List collection
            var bytes = DemoData.File1.Select (x => x + "\ n"). 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");

                // Empty all temporary files in the temporary folder
                Directory.EnumerateFiles (temp) .ToList (). ForEach (File.Delete);
                ClearDownloadDirectory (downloadDir);
                // generate 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");
            }
            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
                {
                }
            }
        }
    }
}
View CodeSecond, run the example


2.1 Here, the Implementation Code section of this example is completed, if we open the address: Http://localhost:63161/download/single, the browser will pop up the file to save the prompt window, as follows:

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






Article: ASP. NET Web Api 2 uses bytearraycontent and streamcontent respectively to implement the download file sample source code (including multi-file compression function)



ASP. NET Web Api 2 implements multi-file package and download file Sample source _


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.