Asp.Net Web Api 2 实现多文件打包并下载文件示例源码
前言
最近由于工作和个人事务,站点也好久没更新了,但这并不影响我对.NET的热情。站点的更新工作还是得想办法抽时间来完成的。
提要
今天利用中午的时间来写一篇关于Asp.Net Web Api下载文件的文章,之前我也写过类似的文章,请见:《ASP.NET(C#) Web Api通过文件流下载文件到本地实例》
本文以这篇文章的基础,提供了ByteArrayContent的下载以及在下载多个文件时实现在服务器对多文件进行压缩打包后下载的功能。
关于本文中实现的在服务器端用.NET压缩打包文件功能的过程中,使用到了一个第方类库:DotNetZip,具体的使用将在正文中涉及。好了,描述了这么多前言,下面我们进入本文示例的正文。
一、创建项目
1.1 首先创建名为:WebApiDownload的Web Api 项目(C#);
1.2 接着新建一个空的控制器,命名为:DownloadController;
1.3 创建一些打包文件和存放临时文件的文件夹(downloads),具体请看本文最后提供的示例项目代码
1.4 打开NuGet程序包管事器,搜索DotNetZip,如下图:
搜索到DotNetZip安装包后,进行安装,以便用于本项目将要实现多文件打包压缩的功能,如下图:
安装完成DotNetZip包后,我们就可以退出NuGet程序包管理器了,因为本项目为示例项目,不需再添加其他的包。
1.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>{"f_1_test_1@example.com","f_1_test_2@example.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@example.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@example.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;}}}
}
1.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 + "\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");// 清空临时文件夹中的所有临时文件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 filezip.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{}}}}
}
二、运行示例
2.1 到此,本示例的实现代码部分就完成了,如果我们此时打开地址:http://localhost:63161/download/single,浏览器会弹出保存文件的提示窗口,如下:
2.2 保存此文件后,打开它我们会看到我们的示例数据已被保存到本地了,如下:
我的网站文章:Asp.Net Web Api 2利用ByteArrayContent和StreamContent分别实现下载文件示例源码(含多文件压缩功能)
Asp.Net Web Api 2 实现多文件打包并下载文件示例源码相关推荐
- php打包压缩下载多大,php多文件打包压缩下载简单示例
调用php中内置扩展ZipArchive类可以进行文件压缩打包下载,(PHP 5>=5.2.0,PHP 7,PECL zip>=1.1.0) 调用php中内置扩展ZipArchive类可以 ...
- C++:FTP文件上传下载(附完整源码)
C++:FTP文件上传下载 FTP文件下载 FTP文件上传 FTP文件下载 #include #include #include #pragma comment(lib, "WinInet. ...
- java文件分割合并_java实现文件分割与合并 类示例源码
[实例简介] [实例截图] [核心代码] package cn.part.com; import java.io.BufferedInputStream; import java.io.Buffere ...
- stl文件html预览,【stl文件在线预览】示例源码
[实例简介] [实例截图] [核心代码] WebViewer - STL var container; var camera, cameraTarget, scene, renderer; var c ...
- ASP.NET Web API实践系列06, 在ASP.NET MVC 4 基础上增加使用ASP.NET WEB API
本篇尝试在现有的ASP.NET MVC 4 项目上增加使用ASP.NET Web API. 新建项目,选择"ASP.NET MVC 4 Web应用程序". 选择"基本&q ...
- 【ASP.NET Web API教程】2.3.3 创建Admin控制器
原文:[ASP.NET Web API教程]2.3.3 创建Admin控制器 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本博客文章,请先看前面的内容. Part 3 ...
- Asp.Net Web API 2第一课——入门
前言 Http不仅仅服务于Web Pages.它也是一个创建展示服务和数据的API的强大平台.Http是简单的.灵活的.无处不在的.你能想象到几乎任何的平台都会有HTTP服务库.HTTP服务可以涉及到 ...
- ASP.NET Web API 使用Swagger生成在线帮助测试文档
ASP.NET Web API 使用Swagger生成在线帮助测试文档 Swagger-UI简单而一目了然.它能够纯碎的基于html+javascript实现,只要稍微整合一下便能成为方便的API在线 ...
- ASP.NET Web API 基本操作(CRUD)
上一篇介绍了ASP.NET Web API的基本知识和原理,这一篇我们通过一个更直观的实例,对产品进行CRUD操作(Create/Read/Update/Delete)来继续了解一下它的基本应用. 创 ...
最新文章
- 基于OpenCV之视频读取,处理和显示框架的搭建(一)
- ffmpeg图片压缩为视频
- 【java作业】2、 编写两个函数,分别使用字节流、字符流实现文件的拷贝;点击按钮,将第三个文本框的字符串的值设置为第一个文本框的字符串+第二个文本框的字符串。
- vim normal 模式下L键
- php右侧弹窗QQ客服,JavaScript_网页右侧悬浮滚动在线qq客服代码示例,网页右侧悬浮滚动QQ在线客服 - phpStudy...
- ASP.NET保存信息总结(Application、Session、Cookie、ViewState和Cache等)
- linux caffe ssd安装错误,ubuntu16.04安装caffe以及各种问题汇总
- PowerDesigner(七)-数据库的生成和修改
- 软件开发中的EJB是什么?
- vs2008 sp1补丁安装到最后一点点的时候,就无法安装下去了 解决方法[转]
- Ci24R1_与Si24R1的通讯兼容,更具性价比的2.4GHz收发芯片
- 数据库应用技术课程设计之商城管理系统
- PhotoScan软件进行无人机数据处理流程
- linux mysql ip_Linux下配置mysql允许指定IP远程访问
- 在mac的m1版本安装nginx
- java 地图坐标转换_百度地图经纬度和地址互转(Java代码)
- OPC客户端连接OPCserver报错或拒绝访问
- 路漫漫远修兮-centos7 oracle 11g 静默安装教程
- 【SW7203】智融新料号SW7203,支持1-4S,双向升降压,路径管理,可搭配SW2303,实现车充、移动电源100W
- 嵌入式Linux 的Cramfs 根文件系统配置成可读可写