服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#服务端图片打包下载实现代码解析

C#服务端图片打包下载实现代码解析

2022-09-24 15:47叶丶梓轩 C#

这篇文章主要介绍了C#服务端图片打包下载实现代码解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

一,设计多图片打包下载逻辑:

1,如果是要拉取腾讯云等资源服务器的图片,

2,我们先把远程图片拉取到本地的临时文件夹,

3,然后压缩临时文件夹,

4,压缩完删除临时文件夹,

5,返回压缩完给用户,

6,用户就去请求下载接口,当下载完后,删除压缩包

二,如下代码,ImageUtil

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
 
namespace Common
{
  /// <summary>
  /// 要引用
  /// System.IO.Compression.FileSystem
  /// System.IO.Compression
  /// </summary>
  public static class ImageUtil
  {
    #region 图片打包下载
    /// <summary>
    /// 下载图片到本地,压缩
    /// </summary>
    /// <param name="urlList">图片列表</param>
    /// <param name="curDirName">要压缩文档的路径</param>
    /// <param name="curFileName">压缩后生成文档保存路径</param>
    /// <returns></returns>
    public static bool ImagePackZip(List<string> urlList, string curDirName, string curFileName)
    {
      return CommonException(() =>
      {
        //1.新建文件夹
        if (!Directory.Exists(curDirName))
          Directory.CreateDirectory(curDirName);
 
        //2.下载文件到服务器临时目录
        foreach (var url in urlList)
        {
          DownPicToLocal(url, curDirName + "\\");
          Thread.Sleep(60);//加个延时,避免上一张图还没下载完就执行下一张图的下载操作
        }
 
        //3.压缩文件夹
        if (!File.Exists(curFileName))
          ZipFile.CreateFromDirectory(curDirName, curFileName); //压缩
 
        //异步删除压缩前,下载的临时文件
        Task.Run(() =>
        {
          if (Directory.Exists(curDirName))
            Directory.Delete(curDirName, true);
        });
        return true;
      });
    }
    /// <summary>
    /// 下载压缩包
    /// </summary>
    /// <param name="targetfile">目标临时文件地址</param>
    /// <param name="filename">文件名</param>
    public static bool DownePackZip(string targetfile, string filename)
    {
      return CommonException(() =>
      {
        FileInfo fileInfo = new FileInfo(targetfile);
        HttpResponse rs = System.Web.HttpContext.Current.Response;
        rs.Clear();
        rs.ClearContent();
        rs.ClearHeaders();
        rs.AddHeader("Content-Disposition", "attachment;filename=" + $"{filename}");
        rs.AddHeader("Content-Length", fileInfo.Length.ToString());
        rs.AddHeader("Content-Transfer-Encoding", "binary");
        rs.AddHeader("Pragma", "public");//这两句解决https的cache缓存默认不给权限的问题
        rs.AddHeader("Cache-Control", "max-age=0");
        rs.ContentType = "application/octet-stream";
        rs.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
        rs.WriteFile(fileInfo.FullName);
        rs.Flush();
        rs.End();
        return true;
      });
    }
 
    /// <summary>
    /// 下载一张图片到本地
    /// </summary>
    /// <param name="url"></param>
    public static bool DownPicToLocal(string url, string localpath)
    {
      return CommonException(() =>
      {
        string fileprefix = DateTime.Now.ToString("yyyyMMddhhmmssfff");
        var filename = $"{fileprefix}.jpg";
 
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Timeout = 60000;
        WebResponse response = request.GetResponse();
        using (Stream reader = response.GetResponseStream())
        {
          FileStream writer = new FileStream(localpath + filename, FileMode.OpenOrCreate, FileAccess.Write);
          byte[] buff = new byte[512];
          int c = 0; //实际读取的字节数
          while ((c = reader.Read(buff, 0, buff.Length)) > 0)
          {
            writer.Write(buff, 0, c);
          }
          writer.Close();
          writer.Dispose();
          reader.Close();
          reader.Dispose();
        }
        response.Close();
        response.Dispose();
 
        return true;
      });
    }
    /// <summary>
    /// 公用捕获异常
    /// </summary>
    /// <param name="func"></param>
    /// <returns></returns>
    private static bool CommonException(Func<bool> func)
    {
      try
      {
        return func.Invoke();
      }
      catch (Exception ex)
      {
        return false;
      }
    }
    #endregion
  }
}

三,测试MVC代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web.Mvc;
 
namespace PackImageZip.Controllers
{
  public class HomeController : Controller
  {
    private static object obj = new object();
    public ActionResult Contact()
    {
      ///锁,多文件请求打包,存在并发情况
      lock (obj)
      {
        var DownPicpath = System.Web.HttpContext.Current.Server.MapPath("/DownPicPackge");//服务器临时文件目录 
        string curFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".zip";
        ///多次请求文件名一样,睡眠一下
        Thread.Sleep(2000);
        ////保存拉取服务器图片文件夹
        string curDirName = $"/{DateTime.Now.ToString("yyyyMMddHHmmssfff")}/";
 
        List<string> urlList = new List<string>();
        urlList.Add("https://cdn.duitang.com/uploads/item/201409/08/20140908155026_RdUwH.thumb.700_0.jpeg");
        urlList.Add("https://cdn.duitang.com/uploads/item/201409/08/20140908155026_RdUwH.thumb.700_0.jpeg");
        urlList.Add("https://cdn.duitang.com/uploads/item/201409/08/20140908155026_RdUwH.thumb.700_0.jpeg");
        urlList.Add("https://cdn.duitang.com/uploads/item/201409/08/20140908155026_RdUwH.thumb.700_0.jpeg");
        var isOk = ImageUtil.ImagePackZip(urlList, DownPicpath + curDirName, $"{DownPicpath}/{curFileName}");
        var json = JsonConvert.SerializeObject(new { isok = isOk.ToString(), curFileName = curDirName });
        return Content(json);
      }
    }
    /// <summary>
    /// 下载压缩包
    /// </summary>
    /// <param name="curFileName">文件名</param>
    /// <returns></returns>
    public ActionResult DownePackZip(string curFileName)
    {
      try
      {
        curFileName = curFileName + ".zip";
        var DownPicpath = System.Web.HttpContext.Current.Server.MapPath("/DownPicPackge");
        var flag = ImageUtil.DownePackZip(DownPicpath + "/" + curFileName, curFileName);
 
        ////flag返回包之后就可以删除包,因为包的已经转为流返回给客户端,无需读取源文件
        if (flag && Directory.Exists(DownPicpath))
          System.IO.File.Delete(DownPicpath + "/" + curFileName);
        return Content(flag.ToString());
      }
      catch (Exception ex)
      {
        return Content(ex.Message);
      }
 
    }
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/May-day/p/11776036.html

延伸 · 阅读

精彩推荐
  • C#如何使用C#从word文档中提取图片

    如何使用C#从word文档中提取图片

    图片和文字是word文档中两种最常见的对象,在微软word中,如果我们想要提取出一个文档内的图片,只需要右击图片选择另存为然后命名保存就可以了,今...

    C#教程网11742021-11-12
  • C#C# FileStream文件读写详解

    C# FileStream文件读写详解

    本文主要介绍C#使用 FileStream 读取数据,写入数据等操作,希望能帮到大家。...

    Fskjb7582021-11-19
  • C#C# 多线程编程技术基础知识入门

    C# 多线程编程技术基础知识入门

    这篇文章主要介绍了C# 多线程编程技术基础知识,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    森大科技9582022-08-28
  • C#c# 中文转拼音without CJK

    c# 中文转拼音without CJK

    本文主要介绍了中文转拼音without CJK,文章篇尾附上源码下载。具有一定的参考价值,下面跟着小编一起来看下吧...

    重典6132021-12-23
  • C#C#使用RSA加密解密文件

    C#使用RSA加密解密文件

    这篇文章主要为大家详细介绍了C#使用RSA加密解密文件,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    Cosmop01itan5742022-07-14
  • C#C#高效反射调用方法类实例详解

    C#高效反射调用方法类实例详解

    在本篇文章中小编给大家分享的是关于C#高效反射调用方法类的相关实例内容,有兴趣的朋友们学习下。...

    ITMFB7982022-07-28
  • C#Winform在DataGridView中显示图片

    Winform在DataGridView中显示图片

    本文主要介绍在DataGridView如何显示图片,简单实用,需要的朋友可以参考下。...

    秦风4372021-11-22
  • C#在C#中如何使用正式表达式获取匹配所需数据

    在C#中如何使用正式表达式获取匹配所需数据

    本文给大家分享C#中如何使用正式表达式获取匹配所需数据 ,非常实用,对正则表达式获取匹配相关知识感兴趣的朋友一起学习吧...

    仙桃小白菜4902021-11-16