.NET 6 文件下载

.NET 6 API中实现文件的下载。

创建HttpHeaderConstant用于指定http头。

cs 复制代码
 public sealed class HttpHeaderConstant
 {
     public const string RESPONSE_HEADER_CONTENTTYPE_STREAM = "application/octet-stream";
     public const string RESPONSE_HEADER_NAME_FILENAME = "fileName";
     public const string RESPONSE_HEADER_CONTEN_DISPOSITION_ATTACHMENT = "attachment";
     public const string RESPONSE_HEADER_APPLICATION_JSON = "application/json";
 }

多文件下载,利用zip进行压缩包处理,可以指定压缩等级。

cs 复制代码
        public async Task<IActionResult> MultiDownloadDocuments(DownloadDocumentParameter downloadDocumentParameter, string? shareFolderPath = null)
        {
            string downloadFileAbsolute = string.Empty;
            var documentDtos = downloadDocumentParameter.Details;
            string exportFileName = "Document_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            try
            {
                string fileExtend = ".zip";
                var appPath = AppDomain.CurrentDomain.BaseDirectory;
                var downloadFileName = Path.Combine(appPath, "TmpFolder");

                if (!Directory.Exists(downloadFileName))
                    Directory.CreateDirectory(downloadFileName);
                if (documentDtos != null && documentDtos.Any())
                {
                    if (documentDtos.Count > 1)
                    {
                        //zip
                        fileExtend = ".zip";
                        exportFileName = exportFileName + fileExtend;
                        downloadFileName = Path.Combine(downloadFileName, exportFileName);
                        using (ZipOutputStream s = new ZipOutputStream(File.Create(downloadFileName)))
                        {
                            s.SetLevel(9); // 0-9, 9 being the highest compression
                            byte[] buffer = new byte[4096];
                            for (int i = 0; i < documentDtos.Count; i++)
                            {
                                string absoluteFile = GetFileFromShareFolder(documentDtos[i].DocumentPath, shareFolderPath);
                                string originalFileName = documentDtos[i].DocumentName;
                                if (File.Exists(absoluteFile))
                                {
                                    FileInfo fileInfo = new FileInfo(absoluteFile);
                                    var zipName = exportFileName;
                                    if (string.IsNullOrEmpty(originalFileName))
                                    {
                                        originalFileName = fileInfo.Name;
                                    }
                                    ZipEntry entry = new ZipEntry(originalFileName);
                                    entry.DateTime = DateTime.Now;
                                    entry.IsUnicodeText = true;
                                    s.PutNextEntry(entry);
                                    using (FileStream fs = File.OpenRead(absoluteFile))
                                    {
                                        int sourceBytes;
                                        do
                                        {
                                            sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                            s.Write(buffer, 0, sourceBytes);
                                        } while (sourceBytes > 0);
                                    }
                                }
                                else
                                {
                                    Log.Error($"MultiDownloadDocuments Error==={originalFileName} {CorProMessage.FileNotExist}");
                                }
                            }
                            s.Finish();
                            s.Close();
                        }
                        downloadFileAbsolute = downloadFileName;
                    }
                    else
                    {
                        string absoluteFile = GetFileFromShareFolder(documentDtos[0].DocumentPath, shareFolderPath);// AgencyCorProConstant.DocumentPrefixPath + "\\" + documentDtos[0].DocumentPath;
                        string originalFileName = documentDtos[0].DocumentName;
                        if (File.Exists(absoluteFile))
                        {
                            if (string.IsNullOrEmpty(originalFileName))
                            {
                                originalFileName = new FileInfo(absoluteFile).Name;
                            }
                            exportFileName = StringEx.ReplaceSpecialChart(originalFileName);
                            downloadFileAbsolute = absoluteFile;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, $"MultiDownloadDocuments failed. {ex.Message}");
            }

            var result = await DownloadDocumentByFilePath(downloadFileAbsolute, exportFileName);
            // Delete tmp file(s)
            if (!string.IsNullOrEmpty(downloadFileAbsolute) && (downloadFileAbsolute.Contains("TmpFolder")) && File.Exists(downloadFileAbsolute))
                File.Delete(downloadFileAbsolute);
            return result;
        }

文件下载方法DownloadDocumentByFilePath:

cs 复制代码
 public async Task<IActionResult> DownloadDocumentByFilePath(string filePath, string? fileDownloadName = null)
 {
     if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath))
     {
         if (string.IsNullOrEmpty(fileDownloadName))
         {
             fileDownloadName = new FileInfo(filePath).Name;
         }
         return new FileContentResult(File.ReadAllBytes(filePath), HttpHeaderConstant.RESPONSE_HEADER_CONTENTTYPE_STREAM) { FileDownloadName = fileDownloadName };
     }
     else
     {
         throw new UserFriendlyException("Not found file");
     }
 }

配置文件中的共享路径获取GetFileFromShareFolder

cs 复制代码
public string GetFileFromShareFolder(string fileName, string? shareFolderPath = null)
{
    var appsetting = _configuration.GetSection("AppSettings").Get<AppSetting>();// IConfiguration _configuration
    if (string.IsNullOrEmpty(shareFolderPath))
    {
        shareFolderPath = appsettings.DocumentPrefixPath;
    }
    string sourcePath = Path.Combine(shareFolderPath, fileName);
    Log.Information($"GetNoticeFromshareFolderPath: {shareFolderPath}");
    Log.Information($"GetNoticeFromshareFileName: {fileName}");

    try
    {
        return sourcePath;
    }
    catch (Exception ex)
    {
        Log.Error($"GetFileFromShareFolder failed. File: {sourcePath}. Message: {ex.Message}. Details: {ex.ToString()}", ex);
        return null;
    }
}
相关推荐
To_OC8 小时前
写了三遍 Todo List,我终于搞懂了 React 父子组件到底怎么通信
前端·javascript·react.js
勇往直前plus8 小时前
Vue3(篇一) 核心概念——响应式模板语法与组件基础
前端·javascript·vue.js
咩咩啃树皮9 小时前
第43篇:Vue3计算属性(computed)完全精讲——缓存机制、依赖计算、业务最优解
前端·vue.js·缓存
小Ti客栈10 小时前
Spring Boot 集成 Springdoc-OpenAPI 与 Knife4j实现接口文档与可视化调试
java·spring boot·后端
徐小夕11 小时前
花了一周,3亿tokens,我开源了一款 Word 文档智能审查平台,文稿自动质检+可视化分析,告别低效人工审核
前端·算法·github
Ai拆代码的曹操11 小时前
Spring 事务 REQUIRES_NEW 嵌套调用:连接池翻倍的秘密
java·后端·spring
动恰客流统计11 小时前
ReID边缘计算视觉统计:餐饮店客流增长的数字化破局路径
java·大数据·运维·人工智能
kyriewen12 小时前
别再乱用useEffect了——你写的10个里有8个不该存在
前端·javascript·react.js
Ivanqhz12 小时前
Rust &‘static str浅析
java·前端·javascript·rust
IT_陈寒13 小时前
SpringBoot这个分页坑,我踩了三天才爬出来
前端·人工智能·后端