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

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

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

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

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

2,我們先把遠程圖片拉取到本地的臨時文件夾,

3,然后壓縮臨時文件夾,

4,壓縮完刪除臨時文件夾,

5,返回壓縮完給用戶,

6,用戶就去請求下載接口,當(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ù)器臨時目錄
        foreach (var url in urlList)
        {
          DownPicToLocal(url, curDirName + "\\");
          Thread.Sleep(60);//加個延時,避免上一張圖還沒下載完就執(zhí)行下一張圖的下載操作
        }

        //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">目標(biāo)臨時文件地址</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; //實際讀取的字節(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
  }
}

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

    }
  }
}

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

相關(guān)文章

最新評論

罗田县| 虹口区| 长丰县| 静海县| 个旧市| 宁国市| 济阳县| 古交市| 卓尼县| 新和县| 大丰市| 徐闻县| 福清市| 青河县| 怀安县| 天水市| 拜城县| 海阳市| 综艺| 江安县| 赣榆县| 乌鲁木齐市| 家居| 龙南县| 芷江| 理塘县| 乌兰浩特市| 福泉市| 滁州市| 昔阳县| 扬州市| 涟源市| 连州市| 新河县| 深圳市| 古浪县| 金平| 江西省| 张家港市| 揭阳市| 宁阳县|