1. 程式人生 > 實用技巧 >C# 網路地址下載

C# 網路地址下載

vs2019 .netcode3.1

using Bps.DTO;
using ICSharpCode.SharpZipLib.Zip;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Zhidian.Common.Utility;
using Zhidian.Common.Utility.Extensions;
using Zhidian.Common.Utility.Results; namespace Bps.ManagerAPI.Controllers { /// <summary> /// 網路地址下載 /// </summary> [SwaggerTag("網路地址下載")] public class DownloadController : Controller { /// <summary> /// 網路地址下載 /// </summary> [HttpPost("/download/zip
")] public void DownloadZip([FromBody]DownloadInput input) { Verify.IfNull(input, "引數不能為空"); Verify.If(input.UrlList == null || input.UrlList.Count == 0, "下載檔案不能為空"); //下載返回壓縮檔名 if (input.ZipName.IsNullOrEmpty()) { input.ZipName
= DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip"; } else if (!input.ZipName.ToLower().EndsWith(".zip")) { input.ZipName += ".zip"; } //使用WebClient 下載檔案 System.Net.WebClient myWebClient = new System.Net.WebClient(); //存 檔名和資料流 Dictionary<string, Stream> dc = new Dictionary<string, Stream>(); //取出字串中資訊 (檔名和地址) foreach (var item in input.UrlList) { if (item.Name.IsNullOrEmpty()) { item.Name = Path.GetFileName(item.Url); } else if (!item.Name.Contains(".")) { item.Name += Path.GetExtension(item.Url); } if (dc.Keys.Contains(item.Name)) { item.Name = Guid.NewGuid().ToString("N")+ Path.GetExtension(item.Url); } //呼叫WebClient 的 DownLoadData 方法 下載檔案 byte[] data = myWebClient.DownloadData(item.Url); Stream stream = new MemoryStream(data);//byte[] 轉換成 流 //放入 檔名 和 stream dc.Add(item.Name, stream);//這裡指定為 .doc格式 (自己可以隨時改) } //呼叫壓縮方法 進行壓縮 (接收byte[] 資料) byte[] fileBytes = ConvertZipStream(dc); Response.ContentType = "application/octet-stream"; Response.Headers.Add("Content-Disposition", "attachment;filename=" + input.ZipName);//檔名和格式(格式可以自己定) Response.Headers.Add("Content-Length", fileBytes.Length.ToString());//檔案大小 Response.Body.Write(fileBytes); //放入byte[] Response.Body.Close(); } /// <summary> /// ZipStream 壓縮 /// </summary> /// <param name="streams">Dictionary(string, Stream) 檔名和Stream</param> /// <returns></returns> public byte[] ConvertZipStream(Dictionary<string, Stream> streams) { byte[] buffer = new byte[6500]; MemoryStream returnStream = new MemoryStream(); var zipMs = new MemoryStream(); using (ZipOutputStream zipStream = new ZipOutputStream(zipMs)) { zipStream.SetLevel(9);//設定 壓縮等級 (9級 500KB 壓縮成了96KB) foreach (var kv in streams) { string fileName = kv.Key; using (var streamInput = kv.Value) { zipStream.PutNextEntry(new ZipEntry(fileName)); while (true) { var readCount = streamInput.Read(buffer, 0, buffer.Length); if (readCount > 0) { zipStream.Write(buffer, 0, readCount); } else { break; } } zipStream.Flush(); } } zipStream.Finish(); zipMs.Position = 0; zipMs.CopyTo(returnStream, zipStream.Length.ToInt()); } returnStream.Position = 0; //Stream轉Byte[] byte[] returnBytes = new byte[returnStream.Length]; returnStream.Read(returnBytes, 0, returnBytes.Length); returnStream.Seek(0, SeekOrigin.Begin); return returnBytes; } } }
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;

namespace Bps.DTO
{
    /// <summary>
    /// 網路地址下載-輸入
    /// </summary>
    public class DownloadInput
    {
        /// <summary>
        /// 下載返回壓縮檔名
        /// </summary>
        public string ZipName { get; set; }

        /// <summary>
        /// 下載網路檔案
        /// </summary>
        [Required]
        public List<DownloadUrlAndName> UrlList { get; set; }
    }

    public class DownloadUrlAndName {

        /// <summary>
        /// 網路地址
        /// </summary>
        [Required]
        public string Url { get; set; }
        /// <summary>
        /// 檔名
        /// </summary>
        public string Name { get; set; }

    }
}

參考:https://www.cnblogs.com/xxxxue/p/11153610.html