欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#服務(wù)端圖片打包下載實(shí)現(xiàn)代碼解析

 更新時(shí)間:2020年07月13日 14:50:45   作者:葉丶梓軒  
這篇文章主要介紹了C#服務(wù)端圖片打包下載實(shí)現(xiàn)代碼解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

一,設(shè)計(jì)多圖片打包下載邏輯:

1,如果是要拉取騰訊云等資源服務(wù)器的圖片,

2,我們先把遠(yuǎn)程圖片拉取到本地的臨時(shí)文件夾,

3,然后壓縮臨時(shí)文件夾,

4,壓縮完刪除臨時(shí)文件夾,

5,返回壓縮完給用戶,

6,用戶就去請(qǐng)求下載接口,當(dāng)下載完后,刪除壓縮包

二,如下代碼,ImageUtil

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.下載文件到服務(wù)器臨時(shí)目錄
        foreach (var url in urlList)
        {
          DownPicToLocal(url, curDirName + "\\");
          Thread.Sleep(60);//加個(gè)延時(shí),避免上一張圖還沒下載完就執(zhí)行下一張圖的下載操作
        }

        //3.壓縮文件夾
        if (!File.Exists(curFileName))
          ZipFile.CreateFromDirectory(curDirName, curFileName); //壓縮

        //異步刪除壓縮前,下載的臨時(shí)文件
        Task.Run(() =>
        {
          if (Directory.Exists(curDirName))
            Directory.Delete(curDirName, true);
        });
        return true;
      });
    }
    /// <summary>
    /// 下載壓縮包
    /// </summary>
    /// <param name="targetfile">目標(biāo)臨時(shí)文件地址</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緩存默認(rèn)不給權(quán)限的問題
        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; //實(shí)際讀取的字節(jié)數(shù)
          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
  }
}

三,測(cè)試MVC代碼

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()
    {
      ///鎖,多文件請(qǐng)求打包,存在并發(fā)情況
      lock (obj)
      {
        var DownPicpath = System.Web.HttpContext.Current.Server.MapPath("/DownPicPackge");//服務(wù)器臨時(shí)文件目錄  
        string curFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".zip";
        ///多次請(qǐng)求文件名一樣,睡眠一下
        Thread.Sleep(2000);
        ////保存拉取服務(wù)器圖片文件夾
        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返回包之后就可以刪除包,因?yàn)榘囊呀?jīng)轉(zhuǎn)為流返回給客戶端,無(wú)需讀取源文件
        if (flag && Directory.Exists(DownPicpath))
          System.IO.File.Delete(DownPicpath + "/" + curFileName);
        return Content(flag.ToString());
      }
      catch (Exception ex)
      {
        return Content(ex.Message);
      }

    }
  }
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • unity實(shí)現(xiàn)手游虛擬搖桿

    unity實(shí)現(xiàn)手游虛擬搖桿

    這篇文章主要為大家詳細(xì)介紹了unity實(shí)現(xiàn)手游虛擬搖桿,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-04-04
  • C# List介紹及具體用法

    C# List介紹及具體用法

    這篇文章主要介紹了C# List介紹及具體用法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-12-12
  • C#使用Objects?Comparer進(jìn)行對(duì)象比較

    C#使用Objects?Comparer進(jìn)行對(duì)象比較

    本文主要介紹了C#使用Objects?Comparer進(jìn)行對(duì)象比較,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-07-07
  • c# 模擬串口通信 SerialPort的實(shí)現(xiàn)示例

    c# 模擬串口通信 SerialPort的實(shí)現(xiàn)示例

    本文主要介紹了c# 模擬串口通信 SerialPort的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-05-05
  • 利用C#自定義一個(gè)時(shí)間類型YearMonth

    利用C#自定義一個(gè)時(shí)間類型YearMonth

    .Net6中加入了兩個(gè)新的時(shí)間類型:DateOnly和TimeOnly,但DateOnly和TimeOnly都有相應(yīng)的應(yīng)用場(chǎng)景,所以本文就來(lái)自定義一個(gè)時(shí)間類型YearMonth,用于解決實(shí)際項(xiàng)目開發(fā)中的需求,希望對(duì)大家有所幫助
    2023-07-07
  • C#中免費(fèi)密碼庫(kù)BouncyCastle的使用詳解

    C#中免費(fèi)密碼庫(kù)BouncyCastle的使用詳解

    這篇文章主要來(lái)和大家分享一個(gè)C#版開源、免費(fèi)的Bouncy?Castle密碼庫(kù):BouncyCastle,文中介紹了BouncyCastle的具體使用,需要的可以參考下
    2024-03-03
  • C# winform點(diǎn)擊生成二維碼實(shí)例代碼

    C# winform點(diǎn)擊生成二維碼實(shí)例代碼

    這篇文章主要介紹了 C# winform點(diǎn)擊生成二維碼實(shí)例代碼,需要的朋友可以參考下
    2017-04-04
  • C#使用foreach語(yǔ)句搜索數(shù)組元素的方法

    C#使用foreach語(yǔ)句搜索數(shù)組元素的方法

    這篇文章主要介紹了C#使用foreach語(yǔ)句搜索數(shù)組元素的方法,涉及C#使用foreach語(yǔ)句遍歷數(shù)組實(shí)現(xiàn)搜索功能的技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下
    2015-04-04
  • C# 拼圖魔方小游戲

    C# 拼圖魔方小游戲

    這篇文章主要介紹了C# 拼圖魔方小游戲,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-02-02
  • C#正則表達(dá)式分解和轉(zhuǎn)換IP地址實(shí)例(C#正則表達(dá)式大全 c#正則表達(dá)式語(yǔ)法)

    C#正則表達(dá)式分解和轉(zhuǎn)換IP地址實(shí)例(C#正則表達(dá)式大全 c#正則表達(dá)式語(yǔ)法)

    這是我發(fā)了不少時(shí)間整理的C#的正則表達(dá)式,新手朋友注意一定要手冊(cè)一下哦,這樣可以節(jié)省很多寫代碼的時(shí)間。下面進(jìn)行了簡(jiǎn)單總結(jié)
    2013-12-12

最新評(píng)論