最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時(shí)間:2020年07月13日 14:50:45   作者:葉丶梓軒  
這篇文章主要介紹了C#服務(wù)端圖片打包下載實(shí)現(xiàn)代碼解析,文中通過(guò)示例代碼介紹的非常詳細(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í),避免上一張圖還沒(méi)下載完就執(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)限的問(wè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)文章

最新評(píng)論

平定县| 理塘县| 高邑县| 托克逊县| 凤庆县| 壤塘县| 邵东县| 西城区| 阿鲁科尔沁旗| 鹤庆县| 黎城县| 阳新县| 恩施市| 会理县| 上蔡县| 洛宁县| 乌鲁木齐市| 哈巴河县| 大石桥市| 霍山县| 揭西县| 三明市| 儋州市| 诸城市| 都兰县| 苍梧县| 吉安市| 西青区| 邓州市| 广平县| 固原市| 五华县| 筠连县| 聂荣县| 松江区| 湖口县| 苗栗市| 苍南县| 西吉县| 琼海市| 井研县|