返回

Spring 控制器文件下载:分步指南与示例

java

通过 Spring 控制器无缝下载文件

作为一名经验丰富的程序员,我经常需要在 Web 应用程序中处理文件下载。Spring 框架为实现这一常见操作提供了强大的支持。本文将探讨如何使用 Spring 控制器有效下载文件,并深入介绍如何通过生成 PDF 并下载来实现此功能。

设置控制器

要处理文件下载请求,我们需要定义一个控制器方法。该方法负责获取要下载的文件并设置正确的 HTTP 头部以指示浏览器进行下载。

@GetMapping("/download")
public ResponseEntity<Resource> downloadFile() {
    // 文件路径
    String filePath = "path/to/file.pdf";
    
    // 获取文件资源
    Resource resource = new FileSystemResource(filePath);
    
    // 设置 HTTP 头部
    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename());
    headers.add(HttpHeaders.CONTENT_TYPE, "application/pdf");
    
    // 返回响应实体
    return ResponseEntity.ok()
            .headers(headers)
            .body(resource);
}

生成 PDF 文件

在某些情况下,您可能需要在控制器中生成 PDF 文件。借助 iText 等第三方库,我们可以轻松地将 Freemarker 模板转换为 PDF。

// 创建 PDF 文档
Document document = new Document();

PdfWriter.getInstance(document, new FileOutputStream("path/to/file.pdf"));
document.open();

// 设置数据模型
Map<String, Object> model = new HashMap<>();
model.put("title", "PDF 文件");
model.put("content", "这是 PDF 文件的内容。");

// 根据模板生成 PDF
Template template = Configuration.getDefaultInstance().getTemplate("freemarker-template.ftl");
template.process(model, new HtmlWriter(document));

document.close();

使用 Spring 下载文件

生成 PDF 文件后,我们可以使用前面定义的控制器方法下载该文件。只需将 PDF 文件路径传递给 downloadFile() 方法即可。

示例

下面是一个完整的示例,展示如何在 Spring 控制器中下载 PDF 文件:

@SpringBootApplication
public class FileDownloadApplication {
    public static void main(String[] args) {
        SpringApplication.run(FileDownloadApplication.class, args);
    }
}

@Controller
public class FileDownloadController {
    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile() {
        // 生成 PDF 文件
        generatePdfFile();

        // 文件路径
        String filePath = "path/to/file.pdf";
        
        // 获取文件资源
        Resource resource = new FileSystemResource(filePath);
        
        // 设置 HTTP 头部
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename());
        headers.add(HttpHeaders.CONTENT_TYPE, "application/pdf");
        
        // 返回响应实体
        return ResponseEntity.ok()
                .headers(headers)
                .body(resource);
    }
    
    private void generatePdfFile() {
        // 根据 Freemarker 模板生成 PDF
        try {
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream("path/to/file.pdf"));
            document.open();
            
            Map<String, Object> model = new HashMap<>();
            model.put("title", "PDF 文件");
            model.put("content", "这是 PDF 文件的内容。");
            
            Template template = Configuration.getDefaultInstance().getTemplate("freemarker-template.ftl");
            template.process(model, new HtmlWriter(document));
            
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

常见问题解答

  • 如何下载其他文件类型?

控制器方法可以处理任何类型的文件。只需更新 Content-Type 头部以匹配文件类型,如 text/plainimage/png

  • 我可以使用流式传输文件吗?

是的,您可以通过使用 @ResponseBody 注解并直接在控制器方法中返回字节数组来流式传输文件。

  • 如何限制文件下载?

您可以在控制器方法中添加安全检查,例如检查用户权限或验证文件是否允许下载。

  • 如何自定义下载文件名?

您可以在 Content-Disposition 头部的 filename 参数中指定自定义下载文件名。

结论

通过 Spring 控制器下载文件是一个简单而有效的过程。通过利用第三方库,您还可以生成和下载不同类型的文件,如 PDF。本指南提供了逐步说明和示例,帮助您轻松实现这一常见 Web 应用程序功能。