我正在尝试使用 Spring MVC 控制器下载 PDF 文件(请参见下面的代码)。然而,尽管使用了“Content-Disposition”,PDF 文件仍会显示在浏览器(Chrome/Firefox/Internet Explorer)中。相反,我希望显示一个“另存为”对话框。有没有人看到我的代码有什么问题,或者我需要额外的弹簧配置才能工作?
@Controller
public class PdfController {
@Autowired
private PdfService pdfService;
@RequestMapping(value = "/" + "temp", method = RequestMethod.GET)
public void downloadPdf(final HttpServletRequest request,
final HttpServletResponse response) throws IOException,
TemplateException, DocumentException {
InputStream pdfInputStream = new ByteArrayInputStream(
pdfService.createPdf());
IOUtils.copy(pdfInputStream, response.getOutputStream());
String filename = "CustomFileName.pdf";
response.setHeader("Content-Disposition", "attachment; filename="
+ filename.replace(" ", "_"));
response.setContentType("application/pdf");
response.flushBuffer();
}
}