springboot實作檔案預覽
如果直接預覽.pdf檔案
由于安全問題,當url為本地路徑的時候,前端不能直接使用window.open(url)打開檔案。
解決方案:
-pom.xml導入
<!-- 檔案格式轉換-->
<dependency>
<groupId>com.artofsolving</groupId>
<artifactId>jodconverter</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>jurt</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>ridl</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>juh</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>unoil</artifactId>
<version>3.0.1</version>
</dependency>
- 寫一個config
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/Path/**").addResourceLocations("file:/E:/file_PDF/");
}
}
前面的路徑為傳回前端的虛拟路徑,後面的 路徑為儲存檔案的本地路徑。
需要檔案格式轉換
- 需要下載下傳officeopen
- 下載下傳完成後進入officeopen.exe 檔案目錄(我的為C:\Program Files (x86)\OpenOffice 4\program\)
- 在目錄下cmd執行
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
- 代碼進行轉換
@RequestMapping("/showPDF")
public String changeType(String fid,String fileName,HttpServletRequest request) throws ConnectException {
String srcPath = "E:\\file_upload\\" + fid + "_" + fileName;
File inputFile = new File(srcPath);
if (!inputFile.exists()){
System.out.println("源檔案不存在!");
return "";
}
// 把檔案名轉化為.pdf結尾
String targetFileName = fileName.substring(0,fileName.lastIndexOf('.')) + ".pdf";
String targetPath = "E:\\file_PDF\\"+fid + "_" + targetFileName;
File outputFile = new File(targetPath);
// 如果這個檔案之前轉換過
// 直接展示
if (outputFile.exists()){
return "/Path/" + fid + "_" + targetFileName;
}
if (!outputFile.getParentFile().exists()){
outputFile.getParentFile().mkdirs();
}
// 調用openoffice服務線程
// 進入officeopen 目錄啟動
//soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard
String command = "C:\\Program Files (x86)\\OpenOffice 4\\program\\soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";
Process p = null;
try {
p = Runtime.getRuntime().exec(command);
} catch (IOException e) {
e.printStackTrace();
}
// 連接配接openoffice服務
OpenOfficeConnection connection = new SocketOpenOfficeConnection(
"127.0.0.1", 8100);
connection.connect();
// 支援轉換txt doc ppt xls檔案到pdf
DocumentConverter converter = new StreamOpenOfficeDocumentConverter(
connection);
converter.convert(inputFile, outputFile);
// 關閉連接配接
connection.disconnect();
// 關閉程序
p.destroy();
System.out.println("轉換完成!");
return "/Path/" + fid + "_" + targetFileName;
}
注意:
由于jodconverter 2.2.1版本不能将.doxc 檔案轉化成pdf。将版本改為2.2.2
2.2.2版本的倉庫裡面沒有需要自己在網上然後下載下傳jar包自己導入