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

posted @ 2020-09-10 18:09  cclon  阅读(290)  评论(0编辑  收藏  举报