通过文件路径获取文件,对不同类型的文件进行不同处理,将Word文件转成pdf文件预览,暂不支持Excel文件,如果浏览器不支持PDF文件预览需要下载插件。
@RequestMapping("previewFile")
public void download(String filePath ,HttpServletRequest request,HttpServletResponse response) throws Exception {
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
String fileName = f.getName();
String extension = getFileExtension(f.getName());
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] bs = new byte[1024];
int len = 0;
response.reset(); // 非常重要
URL u = new URL("file:///" + filePath);
//String contentType = u.openConnection().getContentType();
String contentType = "";
if(extension.equals("pdf")){
contentType = "application/pdf";
}else if (extension.equals("txt")){
contentType = "text/plain";
}else if (extension.equals("doc") || extension.equals("docx")){
contentType = "application/pdf";
try {
br = convertToPdf(filePath);
}catch (Exception e){
}
}else if (extension.equals("jpg") || extension.equals("jpeg")){
contentType = "image/jpeg";
}else if (extension.equals("png")){
contentType = "image/png";
}else if (extension.equals("gif")){
contentType = "image/gif";
}else if (extension.equals("gif")){
contentType = "image/gif";
}
response.setContentType(contentType+"; charset=UTF-8");
response.setHeader("Content-Disposition", "inline;filename="
+ fileName);
// 文件名应该编码成utf-8,注意:使用时,我们可忽略这句
OutputStream out = response.getOutputStream();
while ((len = br.read(bs)) > 0) {
out.write(bs, 0, len);
}
out.flush();
out.close();
br.close();
}
public static String getFileExtension(String fileName) {
if (fileName == null || fileName.isEmpty()) {
return "";
}
int dotIndex = fileName.lastIndexOf('.');
if (dotIndex == -1 || dotIndex == fileName.length() - 1) {
// No dot found or dot is at the end (e.g., "file.")
return "";
}
return fileName.substring(dotIndex + 1);
}
public static BufferedInputStream convertToPdf(String wordFilePath) throws Exception {
// 加载Word文档
Document doc = new Document(wordFilePath);
// 创建一个字节数组输出流来保存PDF内容
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// 设置PDF保存选项(可选,这里使用默认设置)
PdfSaveOptions saveOptions = new PdfSaveOptions();
// 将文档保存为PDF格式到字节数组输出流中
doc.save(byteArrayOutputStream, saveOptions);
// 将字节数组转换为字节输入流
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
// 返回BufferedInputStream
return new BufferedInputStream(byteArrayInputStream);
}