下载远程文件并打包为zip,两种方式,一种直接返回内容下载,一个返回相对路径前端触发下载

//返回路径       
public async Task<ApiResponse<string>> DownFile5(string formId, Dictionary<string, DataTable> dt, string baseurl, Dictionary<string, string> wjj) { LogHelp.WriteLog($"dt:{dt.Count}", "DownFile4"); //自定义的返回结果类 ApiResponse<string> result = new ApiResponse<string>(); try { string key = DateTime.Now.ToString("yyyyMMddHHmmssffffff"); string pathZip = Directory.GetCurrentDirectory() + "/wwwroot/Files/" + key + "/"; foreach (var zd in dt) { string newPath = pathZip + wjj[zd.Key]; if (!Directory.Exists(newPath)) { Directory.CreateDirectory(newPath); } foreach (DataRow item in zd.Value.Rows) { try { string path = (baseurl + "/Services/FileService/redirectDownload.ashx?fileId=" + item["F_FILE_ID"].ToString() + "&viewGUID=" + item["F_VIEW_GUID"].ToString()); string name = item["F_FILE_ORIGINAL_NAME"].ToString(); HttpClient client = new HttpClient(); client.BaseAddress = new Uri(path); //根据文件信息中的文件地址获取远程服务器,返回文件流 LogHelp.WriteLog($"path:{path}--name:{name}", "DownFile4"); var stream = await client.GetStreamAsync(path); LogHelp.WriteLog($"path:{path}--stream:", "DownFile4"); var fils = File(stream, "application/vnd.android.package-archive", name); //创建文件流(文件路径,文件操作.创建) using (FileStream fs = new FileStream(newPath + "/" + name, FileMode.Create)) { //复制文件流 fils.FileStream.CopyTo(fs); } } catch (Exception ex) { LogHelp.WriteLog($"ex:{ex.Message + ex.StackTrace}", "DownFile4-foreach"); } } } LogHelp.WriteLog($"url:{Directory.GetCurrentDirectory() + "/wwwroot/Files/" + key + ".zip"}", "DownFile4"); //对多个文件流所在的目录进行压缩 ZipFile.CreateFromDirectory(pathZip, Directory.GetCurrentDirectory() + "/wwwroot/Files/" + key + ".zip"); LogHelp.WriteLog($"urlZipFile完成:{key}", "DownFile4"); //删除目录以及目录下的子文件 //存在即删除 if (Directory.Exists(pathZip)) { Directory.Delete(pathZip, true); } //result.code = flag ? StatusCodes.Status200OK : StatusCodes.Status417ExpectationFailed; result.path = key + ".zip"; result.message = "压缩成功"; } catch (Exception ex) { result.message = "上传异常,原因:" + ex.Message; } return result; }

  

1、调用 返回下载路径,前端下载

 url =
            window.location.protocol +
            '//' +
            window.location.host +
            '/' +
            res.data

downFile (baseUrl) { if (window.navigator && window.navigator.msSaveOrOpenBlob) { // for IE console.log('ie下载地址' + baseUrl) window.location.href = baseUrl } else { var link = document.createElement('a') link.download = '导出' link.style.display = 'none' link.href = baseUrl document.body.appendChild(link) link.click() document.body.removeChild(link) } }

  

TaiZhangListDataExportPoco自己写的对象,根据需要自行定义即可

[HttpPost]
        public async Task<IActionResult> GetExportFJBySelectedNR([FromBody] TaiZhangListDataExportPoco data)
        {
            try
            {
                
                string oaURL = "http://localhost";
                var task = await DownFile5(formId, dt, oaURL, wjj);
                //_logger.LogInformation("GetExportFJBySelected -> 3 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " | formName = " + formName + " , formId = " + formId);
                LogHelp.WriteLog($"result3:{data.FormName}-{formId}", "GetExportFJBySelected");
                var pathBase = configuration.GetSection("PathBase").Value;
                //_logger.LogInformation("GetExportFJBySelected -> 4 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " |   D.path = " + D.path);
                LogHelp.WriteLog($"result4:path{ task.path}", "GetExportFJBySelected");
                return Success(pathBase + "/Files/" + task.path);

            }
            catch (Exception ex)
            {

                LogHelp.WriteLog($"ex:{ ex.Message + ex.StackTrace}", "GetExportFJBySelected");
                throw ex;
            }

        }

  

2、直接下载输出

        [HttpGet]
        [Route("DownLoadFileZIP")]
        public async Task<IActionResult> DownLoadFileZIP()
        {
            var D = await DownFile2();
            var stream = System.IO.File.OpenRead(D.path);
            string fileExt = Path.GetExtension(D.path);
            var provider = new FileExtensionContentTypeProvider(); //获取文件的ContentType
            var memi = provider.Mappings[fileExt];
            if (System.IO.File.Exists(D.path))
            {
                System.IO.File.Delete(D.path);
            }
            return File(stream, memi, Path.GetFileName(D.path));
        }

  获取路径

        public async Task<ApiResponse<string>> DownFile2()
        {
            //自定义的返回结果类
            ApiResponse<string> result = new ApiResponse<string>();
            try
            {
                //远程下载多个文件的地址
                List<string> filePaths = new List<string>() {
                    "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Ffile1.renrendoc.com%2Ffileroot2%2F2019-12%2F15%2Ffd0c1297-e45a-46f5-98d5-0d2ab707745c%2Ffd0c1297-e45a-46f5-98d5-0d2ab707745c1.gif&refer=http%3A%2F%2Ffile1.renrendoc.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1652520180&t=88ab170ea69b930ac52cdd455f7561e2",
                    "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Ffile2.renrendoc.com%2Ffileroot_temp3%2F2021-10%2F26%2F1cd719ee-5f7b-4e50-99e7-8bd3e716a979%2F1cd719ee-5f7b-4e50-99e7-8bd3e716a9794.gif&refer=http%3A%2F%2Ffile2.renrendoc.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1652520180&t=af992b6d5afe9475507299a1cf70c23d" };

                //多个文件的重命名
                List<string> fileNames = new List<string>() { "cover.jpg", "obj.jpg" };

                //先判断是否保存有上次打包的压缩文件
                if (System.IO.File.Exists(Directory.GetCurrentDirectory() + "/wwwroot/ziliao.zip"))
                {
                    System.IO.File.Delete(Directory.GetCurrentDirectory() + "/wwwroot/ziliao.zip");
                }
                //准备用来存放下载的多个文件流目录
                string pathZip = Directory.GetCurrentDirectory() + "/wwwroot/downfile/";
                for (int i = 0; i < filePaths.Count; i++)
                {
                    string newPath = pathZip + "dir" + i;
                    if (!Directory.Exists(newPath))
                    {
                        Directory.CreateDirectory(newPath);
                    }
                    string path = filePaths[i];
                    HttpClient client = new HttpClient();
                    client.BaseAddress = new Uri(path);
                    //根据文件信息中的文件地址获取远程服务器,返回文件流
                    var stream = await client.GetStreamAsync(path);

                    var fils = File(stream, "application/vnd.android.package-archive", Path.GetFileName(path));
                    //创建文件流(文件路径,文件操作.创建)
                    using (FileStream fs = new FileStream(newPath + "/" + fileNames[i], FileMode.Create))
                    {
                        //复制文件流
                        fils.FileStream.CopyTo(fs);
                    }
                }
                //对多个文件流所在的目录进行压缩
                ZipFile.CreateFromDirectory(Directory.GetCurrentDirectory() + "/wwwroot/downfile/", Directory.GetCurrentDirectory() + "/wwwroot/" + "ziliao.zip");
                //删除目录以及目录下的子文件
                //存在即删除
                if (Directory.Exists(pathZip))
                {
                    Directory.Delete(pathZip, true);
                }
                //result.code = flag ? StatusCodes.Status200OK : StatusCodes.Status417ExpectationFailed;
                result.path = Directory.GetCurrentDirectory() + "\\wwwroot\\" + "ziliao.zip";
                result.message = "压缩成功";
            }
            catch (Exception ex)
            {
                result.message = "上传异常,原因:" + ex.Message;
            }
            return result;
        }

  标准参数

1    public class ApiResponse<T>
2     {
3         public string message;
4         public string path;
5     }

 

posted @ 2022-04-22 22:58  无定的界  阅读(434)  评论(0)    收藏  举报