[HttpGet][Route("downloadimgszip")]public void downloadimages(string goodsid){//获取所有图片路径List<string> arraylist = GetAllImagePathsByGoodId(goodsid);var DownPicpath = System.Web.HttpContext.Current.Server.MapPath("/DownPicPackge");//获取IIS服务器临时文件目录 //创建文件夹 if (!Directory.Exists(DownPicpath))Directory.CreateDirectory(DownPicpath);var siteconfig = _configCache.GetConfigSiteGlobal();foreach (var item in arraylist){//从oss服务器上下载图片文件到IIS服务器临时目录文件夹var client = new OssClient(siteconfig.remote_oss_host, siteconfig.remote_oss_accesskey, siteconfig.remote_oss_accesssecret);// 下载文件到流。OssObject 包含了文件的各种信息,如文件所在的存储空间、文件名、元信息以及一个输入流。//这里的item需要注意格式,例如:1233/123.jpg, 路径第一个字符前要是有斜线的一定要去掉,否则会报错var obj = client.GetObject(siteconfig.remote_oss_bucketname, item);var downloadFilename = Path.GetFileName(item);using (var requestStream = obj.Content){byte[] buf = new byte[1024];var fs = File.Open(DownPicpath + "/" + downloadFilename, FileMode.OpenOrCreate);var len = 0;// 通过输入流将文件的内容读取到文件或者内存中。while ((len = requestStream.Read(buf, 0, 1024)) != 0){fs.Write(buf, 0, len);}fs.Close();}}//声明压缩文件名string zipName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".zip";if (File.Exists(zipName)){File.Delete(zipName);}CreateZipFile(DownPicpath, DownPicpath + "/" + zipName);//通知浏览器下载文件而不是打开 FileStream fsstream = new FileStream(DownPicpath + "/" + zipName, FileMode.Open);byte[] bytes = new byte[(int)fsstream.Length];fsstream.Read(bytes, 0, bytes.Length);fsstream.Close();System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";//通知浏览器下载文件而不是打开 System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(zipName, System.Text.Encoding.UTF8));System.Web.HttpContext.Current.Response.BinaryWrite(bytes);System.Web.HttpContext.Current.Response.Flush();System.Web.HttpContext.Current.Response.End();//异步删除压缩前,下载的临时文件Task.Run(() =>{if (Directory.Exists(curDirName))Directory.Delete(curDirName, true);});}/// <summary>/// 创建压缩文件/// </summary>/// <param name="filesPath"></param>/// <param name="zipFilePath"></param>private static void CreateZipFile(string filesPath, string zipFilePath){ if (!Directory.Exists(filesPath)){Console.WriteLine("Cannot find directory '{0}'", filesPath);return;} string[] filenames = Directory.GetFiles(filesPath);using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath))){s.SetLevel(9); // 压缩级别 0-9//s.Password = "123"; //Zip压缩文件密码byte[] buffer = new byte[4096]; //缓冲区大小foreach (string file in filenames){ZipEntry entry = new ZipEntry(Path.GetFileName(file));entry.DateTime = DateTime.Now;s.PutNextEntry(entry);using (FileStream fs = File.OpenRead(file)){int sourceBytes;do{sourceBytes = fs.Read(buffer, 0, buffer.Length);s.Write(buffer, 0, sourceBytes);} while (sourceBytes > 0);}}s.Finish();s.Close();}}
如果代码对您有帮助,帮忙打个赏,支持原创,感谢老铁们的支持。。