Java pdf文件传输_java中pdf文件的管理(pdf文件转png文件,base64传输文件以及删除)...
org.apache.pdfbox
pdfbox
2.0.12
影像文件轉(zhuǎn)為base64編碼使用java自帶的BASE64Encoder類
代碼部分:
前端上傳文件的保存:
@RequestMapping("upLoadImgs")
@ResponseBodypublic String upLoadAgreementsImg(HttpServletResponse response, HttpServletRequest request) throwsException {//獲取前臺(tái)傳輸?shù)奈募?shù)據(jù)
MultipartHttpServletRequest mreq =(MultipartHttpServletRequest) request;
JSONObject rt= newJSONObject();//默認(rèn)保存成功,失敗時(shí)再修改對(duì)應(yīng)狀態(tài)
rt.put("status",0);
rt.put("message","文件保存成功");//上傳的合同影像列表
Iterator fileNames =mreq.getFileNames();
MultipartFile file= null;
String fileName= null;//文件保存地址,從配置文件中獲取 :F:\imgs
String folderPath = ResourceBundle.getBundle("systemconfig").getString("imagesDownloadPath");//自定義影像文件的名字(以當(dāng)前系統(tǒng)時(shí)間+編碼區(qū)分)
String imgName = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");//用來(lái)區(qū)分同次上傳多個(gè)文件的命名計(jì)數(shù)器01,02,03
int count = 1;//循環(huán)存入前端傳來(lái)的影像文件
while(fileNames.hasNext()) {
String countStr= "0";
fileName=(String) fileNames.next();
file=mreq.getFile(fileName);if (file == null) {
logger.info("影像件上傳;文件已損壞,請(qǐng)稍后再試");
rt.put("status",1);
rt.put("message", "文件已損壞,請(qǐng)稍后再試");
}//獲取前臺(tái)傳參文件名
fileName =file.getOriginalFilename();//創(chuàng)建上傳文件目錄
File folder = newFile(folderPath);if (!folder.exists()) {
folder.mkdirs();
}//獲取文件的后綴名
String extension = fileName.substring(fileName.lastIndexOf("."));//保存的文件名
String saveName = imgName + countStr + Integer.toString(count++);
String savePath= folderPath + File.separator + saveName +extension;try{
file.transferTo(newFile(savePath));
}catch(IOException e) {
e.printStackTrace();
rt.put("status",1);
rt.put("message", "文件保存失敗");
}//如果上傳的是pdf文件,轉(zhuǎn)換為png文件
if(extension.equals(".pdf")){//轉(zhuǎn)換為jpg文件
try{
pdf2Png(savePath,folderPath,300,1);
}catch(IOException e) {
e.printStackTrace();
rt.put("status",1);
rt.put("message", "pdf縮略圖保存失敗");
}
}
logger.info("file path:" +savePath);
}returnrt.toJSONString();
}
pdf文件轉(zhuǎn)為png文件,并將轉(zhuǎn)換后的png文件保存到pdf同級(jí)指定文件夾中:
這里需要注意的是,使用PDDocument?對(duì)象轉(zhuǎn)換pdf文件后,使用該對(duì)象的close()方法關(guān)閉,不然會(huì)導(dǎo)致對(duì)應(yīng)的pdf文件時(shí)出現(xiàn)因文件被占用而導(dǎo)致無(wú)法刪除。
/*** 把pdf文件轉(zhuǎn)換為jpg文件同步保存到服務(wù)器上
*@paramsavePath 保存的pdf文件路徑
*@paramfolderPath 文件所在的文件夾
*@paramdpi 轉(zhuǎn)換后的文件清晰度,
*@paramflag 轉(zhuǎn)換的pdf文件頁(yè)數(shù),為0時(shí)轉(zhuǎn)換全部頁(yè)數(shù),也可以指定轉(zhuǎn)換頁(yè)數(shù)
*@throwsException*/
private void pdf2Png (String savePath,String folderPath,int dpi,int flag) throwsException {//獲取pdf文件
File file = newFile(savePath);
PDDocument pdDocument;//創(chuàng)建生成的文件保存路徑
String newFolderPath = folderPath +File.separator+ "thumbnail";
File folder= newFile(newFolderPath);if (!folder.exists()) {
folder.mkdirs();
}//轉(zhuǎn)換新的文件名,123.pdf轉(zhuǎn)換為123.png
int dot = file.getName().lastIndexOf(".");
String imgName= file.getName().substring(0, dot);
pdDocument=PDDocument.load(file);
PDFRenderer renderer= newPDFRenderer(pdDocument);int pages =pdDocument.getNumberOfPages();//確定要打印的頁(yè)數(shù)
if (flag > 0) {if (flag
pages=flag;
}
}//生成新的文件
StringBuffer imgFilePath = null;for (int i = 0; i < pages; i++) {
String imgSavePath= newFolderPath + File.separator +imgName;
imgFilePath= newStringBuffer();
imgFilePath.append(imgSavePath);//因?yàn)橹晦D(zhuǎn)換1頁(yè),所以生成的圖片只有一張,不用分開(kāi)命名,如果轉(zhuǎn)換多頁(yè)pdf文件到多個(gè)png圖片,須加上命名區(qū)分//imgFilePath.append("-");//imgFilePath.append(String.valueOf(i + 1));
imgFilePath.append(".png");
File dstFile= newFile(imgFilePath.toString());
BufferedImage image=renderer.renderImageWithDPI(i, dpi);//引入一個(gè)輸出流,方便關(guān)閉,不然會(huì)因?yàn)槲募徽加枚鴮?dǎo)致無(wú)法刪除
OutputStream ops = newFileOutputStream(dstFile);
ImageIO.write(image,"png", dstFile);
pdDocument.close();
ops.close();
}
}
根據(jù)文件路徑查詢?cè)撀窂较碌乃杏跋裎募?#xff0c;組裝成json返回給前臺(tái),注意的是pdf文件和其對(duì)應(yīng)的png文件組裝在同一個(gè)JsonObject中,方便前臺(tái)顯示:
/***
*@paramimgPath 要查找的文件路徑
*@return返回對(duì)應(yīng)的查詢狀態(tài)值和文件對(duì)應(yīng)的base64編碼
*@throwsException*/
public String queryAgreementsImgByProvOid(String imgPath) throwsException {
JSONObject rt= newJSONObject();//默認(rèn)狀態(tài)為查不到數(shù)據(jù),查到數(shù)據(jù)后修改為0
rt.put("status",1);
String filePath= "";//服務(wù)器保存地址為null直接返回查詢失敗
if(!StringUtil.isEmpty(imgPath)) {
File file= newFile(filePath);//判斷該路徑是否存在
if (!file.exists()) {
rt.put("message", "沒(méi)有相應(yīng)的影像件");
}else{
File[] files=file.listFiles();//多個(gè)文件放在json數(shù)組里
JSONArray imgArray = newJSONArray();for (int i = 0; i < files.length; i++) {if(files[i].isFile()) {
JSONObject imgJson= newJSONObject();
String imgName=files[i].getName();
String imgBASE64Encoder=Base64Util.img2BASE64Encoder(files[i]);//如果是pdf文件,把對(duì)應(yīng)的png、文件也轉(zhuǎn)為base64編碼傳給前臺(tái)
if (imgName.endsWith(".pdf")) {//找到對(duì)應(yīng)的png文件的文件地址
StringBuffer imgPngFileName = newStringBuffer();
imgPngFileName.append(filePath+ File.separator + "thumbnail");int dot = imgName.lastIndexOf(".");
imgPngFileName.append(File.separator+ imgName.substring(0, dot) + ".png");
File pngFile= newFile(imgPngFileName.toString());//如果不存在,返回給前臺(tái)對(duì)應(yīng)的狀態(tài)碼
if(!pngFile.exists()){
imgJson.put("thumbnail", "");
}else{
String pngBASE64Encoder=Base64Util.img2BASE64Encoder(pngFile);
imgJson.put("thumbnail", pngBASE64Encoder);
}
}//組裝進(jìn)json對(duì)象里,方便返回給前臺(tái)
imgJson.put("fileName", imgName);
imgJson.put("fileValue", imgBASE64Encoder);
imgArray.add(imgJson);
}
}if (imgArray.size() != 0) {
rt.put("status", 0);
rt.put("imgs", imgArray);
}else{
rt.put("message", "沒(méi)有相應(yīng)的影像件");
}
}
}else{
rt.put("message", "沒(méi)有相應(yīng)的影像件");
}returnrt.toJSONString();
}
其中Base64Util.img2BASE64Encoder(pngFile)的代碼如下:
/*** 圖片轉(zhuǎn)為base64編碼,其他文件也是通用的
*@paramfile 要轉(zhuǎn)換的文件
*@return*@throwsException*/
public static String img2BASE64Encoder(File file) throwsException{
InputStream in= null;byte[] data = null;try{//讀取圖片字節(jié)數(shù)組
in = newFileInputStream(file);
data= new byte[in.available()];
in.read(data);
in.close();
}catch(IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder= newBASE64Encoder();//返回Base64編碼過(guò)的字節(jié)數(shù)組字符串
returnencoder.encode(data);
}
根據(jù)路徑刪除該路徑下的選中的影像文件,pdf文件同時(shí)刪除與之對(duì)應(yīng)的png文件:
/***
*@paramdelFilePath 要?jiǎng)h除的文件路徑
*@paramfileNames 要?jiǎng)h除的文件列表
*@return根據(jù)刪除狀態(tài)返回給前臺(tái)對(duì)應(yīng)的狀態(tài)值
*@throwsException*/
public String delImgsByPath(String delFilePath, List fileNames) throwsException {
JSONObject rt= newJSONObject();
rt.put("status",0);
rt.put("message", "文件刪除成功");if(StringUtil.isEmpty(delFilePath) || fileNames.size()==0){
rt.put("status", 1);
rt.put("message", "刪除數(shù)據(jù)出錯(cuò),請(qǐng)聯(lián)系相關(guān)人員");
}//根據(jù)文件路徑開(kāi)始刪除
if(!StringUtil.isEmpty(delFilePath)){
String fulllFileName= "";for (int j = 0; j < fileNames.size(); j++) {
String name=fileNames.get(j);//要?jiǎng)h除的文件完整路徑名
fulllFileName = delFilePath + File.separator +name;
File delFile= newFile(fulllFileName);if(delFile.exists()) {if (!delFile.delete()) {
rt.put("status", 1);
rt.put("message", "文件刪除失敗,請(qǐng)稍后重試");
}
}if (name.endsWith(".pdf")) {
StringBuffer imgPngFileName= newStringBuffer();
imgPngFileName.append(delFilePath+ File.separator + "thumbnail");int dot = name.lastIndexOf(".");
imgPngFileName.append(File.separator+ name.substring(0, dot) + ".png");
File pngFile= newFile(imgPngFileName.toString());if(pngFile.exists()){if (!pngFile.delete()) {
rt.put("status", 1);
rt.put("message", "文件刪除失敗,請(qǐng)稍后重試");
}
}
}
}
}returnrt.toJSONString();
}
以上就是對(duì)影像文件進(jìn)行增,刪,查的功能的代碼,其中pdf文件由于文件類型特殊,前段無(wú)法顯示pdf文件的縮略圖進(jìn)行選中刪除操作,所以把pdf文件轉(zhuǎn)換為png文件后再保存到指定的文件夾中,查詢的時(shí)候一起組裝為一個(gè)json對(duì)象里傳給前臺(tái),方便前臺(tái)的顯示,刪除時(shí)同時(shí)把pdf文件對(duì)應(yīng)的png文件刪除,防止占用內(nèi)存空間。關(guān)于pdf文件在前段無(wú)法生成縮略圖這個(gè)問(wèn)題的解決方案,還在持續(xù)的學(xué)習(xí)中,如果有好的建議,歡迎留言大家一起學(xué)習(xí)。
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的Java pdf文件传输_java中pdf文件的管理(pdf文件转png文件,base64传输文件以及删除)...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。