从服务器文件系统中的文件加载pdf浏览器?
问题内容:
如何获取位于服务器目录结构中文件中的pdf,以便在浏览器中为 Spring MVC 应用程序的用户加载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();}
}
问题答案:
更改
res.setHeader("Content-Disposition", "attachment;filename=report.pdf");
至
res.setHeader("Content-Disposition", "inline;filename=report.pdf");
您还应该设置内容长度
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());
}
}