Cod*_*Med 1 pdf spring spring-mvc
如何获取位于服务器目录结构中文件中的pdf,以便在浏览器中为Spring MVC应用程序的用户加载pdf ?
我已经在Google上进行了搜索,并发现了有关如何生成PDF的帖子,但是在这种情况下他们的答案不起作用。例如,此其他发布不相关,因为res.setContentType("application/pdf");在我下面的代码中不能解决问题。另外,此其他文章描述了如何从数据库执行此操作,但未显示完整的工作控制器代码。其他帖子也有类似的问题,导致它们在这种情况下无法工作。
我只需要提供一个文件(而不是来自数据库),并让用户在其浏览器中可以查看它。我想出的最好的是下面的代码,它要求用户下载PDF或在浏览器之外的单独应用程序中查看它。我可以对下面的特定代码进行哪些特定更改,以便用户在单击链接时自动看到其浏览器中的PDF内容,而不提示您下载该PDF内容?
@RequestMapping(value = "/test-pdf")
public void generatePdf(HttpServletRequest req,HttpServletResponse res){
res.setContentType("application/pdf");
res.setHeader("Content-Disposition", "attachment;filename=report.pdf");
ServletOutputStream outStream=null;
try {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(new File("/path/to", "nameOfThe.pdf")));
/*ServletOutputStream*/ outStream = res.getOutputStream();
//to make it easier to change to 8 or 16 KBs
int FILE_CHUNK_SIZE = 1024 * 4;
byte[] chunk = new byte[FILE_CHUNK_SIZE];
int bytesRead = 0;
while ((bytesRead = bis.read(chunk)) != -1) {outStream.write(chunk, 0, bytesRead);}
bis.close();
outStream.flush();
outStream.close();
}
catch (Exception e) {e.printStackTrace();}
}
Run Code Online (Sandbox Code Playgroud)
更改
res.setHeader("Content-Disposition", "attachment;filename=report.pdf");
Run Code Online (Sandbox Code Playgroud)
至
res.setHeader("Content-Disposition", "inline;filename=report.pdf");
Run Code Online (Sandbox Code Playgroud)
您还应该设置内容长度
FileCopyUtils很方便:
@Controller
public class FileController {
@RequestMapping("/report")
void getFile(HttpServletResponse response) throws IOException {
String fileName = "report.pdf";
String path = "/path/to/" + fileName;
File file = new File(path);
FileInputStream inputStream = new FileInputStream(file);
response.setContentType("application/pdf");
response.setContentLength((int) file.length());
response.setHeader("Content-Disposition", "inline;filename=\"" + fileName + "\"");
FileCopyUtils.copy(inputStream, response.getOutputStream());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1503 次 |
| 最近记录: |