Spring mvc Spring MVC-在web浏览器中显示PDF文件
我正在尝试使用SpringMVC在web浏览器中显示PDF文件Spring mvc Spring MVC-在web浏览器中显示PDF文件,spring-mvc,Spring Mvc,我正在尝试使用SpringMVC在web浏览器中显示PDF文件 public void displayActiviteFiles (Activite activite, HttpServletResponse response) throws IOException { File file = new File(activite.getLienUploadUn()); FileInputStream inputStream = new FileInputStream(file);
public void displayActiviteFiles (Activite activite, HttpServletResponse response) throws IOException {
File file = new File(activite.getLienUploadUn());
FileInputStream inputStream = new FileInputStream(file);
IOUtils.copy(inputStream, response.getOutputStream());
response.setHeader("Content-Disposition", "attachment; filename="+file.getName());
response.setContentType("application/pdf");
response.flushBuffer();
}
但我得到的是奇怪的字符,而不是pdf内容。我错在哪里?要回答我的问题并帮助其他人解决我的问题,可以这样做:
File file = new File(activite.getLienUploadUn());
FileInputStream inputStream = new FileInputStream(file);
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1)
{
baos.write(buffer, 0, bytesRead);
}
response.setHeader("Content-Disposition","inline; filename=\""+file.getName()+"\"");
response.setContentType("application/pdf");
ServletOutputStream outputStream = response.getOutputStream();
baos.writeTo(outputStream);
outputStream.flush();
如果这对任何人都很重要,那么这就是spring boot 1.5.11中的100%工作解决方案。还没有在手动Spring MVC项目上运行。也许通过一些小的调整,可以让它工作
@GetMapping(value = "/downloadFile")
public StreamingResponseBody getSteamingFile(HttpServletResponse response) throws URISyntaxException {
File file = new File(getClass().getClassLoader().getResource("templates/more/si.pdf").toURI());
//viewing in web browser
response.setContentType("application/pdf");
//for downloading the file directly if viewing is not possible
response.setHeader("Content-Disposition", "inline; filename=" + file.getName());
file = null;
//put the directory architecture according to your target directory
// generated during compilation in maven spring boot
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("templates/more/si.pdf");
return outputStream -> {
int nRead;
byte[] data = new byte[1024];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
outputStream.write(data, 0, nRead);
}
inputStream.close();
};
}
您可以显示包含此代码的内容
@GetMapping(value = "/pdf")
public void showPdf(HttpServletResponse response) throws IOException {
response.setContentType("application/pdf");
InputStream inputStream = new FileInputStream(new File("/sample.pdf"));
int nRead;
while ((nRead = inputStream.read()) != -1) {
response.getWriter().write(nRead);
}
}