ASPNET 文件批量下载
程序员文章站
2022-04-17 19:57:13
HTML JS API public ActionResult BatchDownloadFiles(string str, int type) { var idList = str.Split(',').ToList().ConvertAll(x => int.Parse(x)); MemoryS ......
html
<a class="btn btn-warning" id="btndownload">选中下载</a>
js
/* 批量下载 */ // li 列表的文件下载 $("#btndownload").on('click', function() { var arr = []; var urls = escape(arr.join(',')); $(this).attr('href', '@url.action("batchdownloadfiles")?str=' + urls + '&r=' + math.random()); });
api
public actionresult batchdownloadfiles(string str, int type) { var idlist = str.split(',').tolist().convertall(x => int.parse(x)); memorystream ms = new memorystream(); zipoutputstream zos = new zipoutputstream(ms); zos.isstreamowner = false; zos.setlevel(1);//设置压缩级别 var rsp = new getlistbydetailidlistrequest { userid = currentuserid, jobtypeid = type, idlist = idlist }.getresponse(); if (rsp.issuccess) { rsp.data.foreach(dto => { var filebyte = byteofgetorderfiles(dto); //byte类型的数据 zipentry entry = new zipentry(filename); //定义新的压缩数据对象 zos.putnextentry(entry); zos.write(filebyte, 0, filebyte.length); //写入 }); } zos.finish(); zos.close(); ms.position = 0; return file(ms, "application/x-zip-compressed", string.format("批量下载文件-{0}.zip", datetime.now.tostring("yyyy年mm月dd hh时mm分ss秒"))); } public byte[] byteofgetorderfiles(extractrecorddetaildto dto) { var stream = downloadfile(dto.sourcefile); byte[] buffur = new byte[stream.length]; stream.read(buffur, 0, (int)stream.length); return buffur; } public static stream downloadfile(string path) { using (var client = new webclient()) { var stream = client.downloaddata(path); var outstream = new memorystream(stream); return outstream; } }