如何实现从数据表下载选中PDF文件?附控制器代码示例
批量下载选中PDF文件的控制器实现
以下是实现从指定目录批量下载选中PDF文件并打包为ZIP的控制器代码(添加中文注释):
[HttpPost] public FileResult DownloadSelectedPdfs(string files) { // 获取当前日期,格式为"日-月-年" string currentDate = DateTime.Now.Date.ToString("dd-MM-yyyy"); // 拼接存储PDF文件的目标目录路径 string dir = filepath + "/" + currentDate + "/"; // 将传入的选中文件名列表按逗号分割成数组 string[] fileList = files.Split(","); int fileCount = fileList.Length; try { // 记录日志:用户进入下载操作 _log.LogInformation("用户 " + HttpContext.Session.GetString("UserName") + " 进入批量下载操作"); // 创建内存流用于存储ZIP文件内容 using (var memoryStream = new MemoryStream()) { // 创建ZIP归档,模式为创建,最后一个参数表示保持流打开 using (var zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) { // 遍历所有选中的文件,逐个添加到ZIP包中 for (int i = 0; i < fileCount; i++) { zipArchive.CreateEntryFromFile(dir + fileList[i], fileList[i]); } } // 将内存流中的ZIP内容返回给客户端,指定MIME类型为ZIP,文件名固定为Attachments.zip return File(memoryStream.ToArray(), "application/zip", "Attachments.zip"); } } catch (Exception ex) { // 记录异常堆栈信息 _log.LogError(ex.StackTrace); // 异常时返回null return null; } }
代码功能说明
- 该接口为
HttpPost请求类型,接收前端传入的选中文件名字符串(以逗号分隔)。 - 基于当前日期拼接文件存储目录,从对应目录读取文件并打包成ZIP格式。
- 操作过程中记录用户操作日志和异常信息。
- 最终将ZIP文件以流式方式返回给客户端供下载。
内容的提问来源于stack exchange,提问作者chethan
相关产品推荐
相关产品推荐

