一、首先工程中增長mvn相關jar:java
<!--pdf生成jar包--> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.4.2</version> </dependency>
二、編寫測試用例web
package com.zdnst.test; import java.io.File; import java.io.FileOutputStream; import com.itextpdf.text.Document; import com.itextpdf.text.Element; import com.itextpdf.text.Font; import com.itextpdf.text.Paragraph; import com.itextpdf.text.Phrase; import com.itextpdf.text.Rectangle; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import com.zdnst.common.utils.FileStorageUtils; public class BasePDFWrite { Document document = null;// 創建一個Document對象 private static Font headFont ; private static Font keyFont ; private static Font textfont_H ; private static Font textfont_B ; int maxWidth = 520; static{ BaseFont bfChinese_H; try { /** * 新建一個字體,iText的方法 STSongStd-Light 是字體,在iTextAsian.jar 中以property爲後綴 * UniGB-UCS2-H 是編碼,在iTextAsian.jar 中以cmap爲後綴 H 表明文字版式是 橫版, 相應的 V 表明豎版 */ bfChinese_H = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED); headFont = new Font(bfChinese_H, 10, Font.NORMAL); keyFont = new Font(bfChinese_H, 18, Font.BOLD); textfont_H = new Font(bfChinese_H, 10, Font.NORMAL); textfont_B = new Font(bfChinese_H, 12, Font.NORMAL); } catch (Exception e) { e.printStackTrace(); } } /** * 設置頁面屬性 * @param file */ public BasePDFWrite(File file) { //自定義紙張 Rectangle rectPageSize = new Rectangle(350, 620); // 定義A4頁面大小 //Rectangle rectPageSize = new Rectangle(PageSize.A4); rectPageSize = rectPageSize.rotate();// 加上這句能夠實現頁面的橫置 document = new Document(rectPageSize,10, 150, 10, 40); try { PdfWriter.getInstance(document,new FileOutputStream(file)); document.open(); } catch (Exception e) { e.printStackTrace(); } } /** * 建表格(以列的數量建) * @param colNumber * @return */ public PdfPTable createTable(int colNumber){ PdfPTable table = new PdfPTable(colNumber); try{ //table.setTotalWidth(maxWidth); //table.setLockedWidth(true); table.setHorizontalAlignment(Element.ALIGN_CENTER); table.getDefaultCell().setBorder(1); table.setSpacingBefore(10); table.setWidthPercentage(100); }catch(Exception e){ e.printStackTrace(); } return table; } /** * 建表格(以列的寬度比建) * @param widths * @return */ public PdfPTable createTable(float[] widths){ PdfPTable table = new PdfPTable(widths); try{ //table.setTotalWidth(maxWidth); //table.setLockedWidth(true); table.setHorizontalAlignment(Element.ALIGN_CENTER); table.getDefaultCell().setBorder(1); table.setSpacingBefore(10); table.setWidthPercentage(100); }catch(Exception e){ e.printStackTrace(); } return table; } /** * 表格中單元格 * @param value * @param font * @param align * @return */ public PdfPCell createCell(String value,Font font,int align){ PdfPCell cell = new PdfPCell(); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setHorizontalAlignment(align); cell.setPhrase(new Phrase(value,font)); return cell; } /** * 表格中單元格 * @param value * @param font * @param align * @param colspan * @param rowspan * @return */ public PdfPCell createCell(String value,Font font,int align_v,int align_h,int colspan,int rowspan){ PdfPCell cell = new PdfPCell(); cell.setVerticalAlignment(align_v); cell.setHorizontalAlignment(align_h); cell.setColspan(colspan); cell.setRowspan(rowspan); cell.setPhrase(new Phrase(value,font)); return cell; } /** * 建短語 * @param value * @param font * @return */ public Phrase createPhrase(String value,Font font){ Phrase phrase = new Phrase(); phrase.add(value); phrase.setFont(font); return phrase; } /** * 建段落 * @param value * @param font * @param align * @return */ public Paragraph createParagraph(String value,Font font,int align){ Paragraph paragraph = new Paragraph(); paragraph.add(new Phrase(value,font)); paragraph.setAlignment(align); return paragraph; } public void generatePDF() throws Exception{ //頁頭信息 document.add(createParagraph("【XXXX有限公司】",headFont,Element.ALIGN_LEFT)); document.add(createParagraph("籤 購 單",keyFont,Element.ALIGN_CENTER)); document.add(createParagraph("編號:XD201602000003",headFont,Element.ALIGN_RIGHT)); //表格信息 float[] widths = {4f,10f,10f,20f,15f,8f,11f,12f,10f}; PdfPTable table = createTable(widths); table.addCell(createCell("顧客信息", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,4)); table.addCell(createCell("顧客名稱", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,2,1)); table.addCell(createCell("XXXX有限公司", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,6,1)); table.addCell(createCell("編碼/稅號", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,2,1)); table.addCell(createCell("", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,6,1)); table.addCell(createCell("聯繫地址", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,2,1)); table.addCell(createCell("", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,6,1)); table.addCell(createCell("採購經辦人", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,2,1)); table.addCell(createCell("", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("經辦人電話", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,1)); table.addCell(createCell("", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,2,1)); table.addCell(createCell("經辦人手機", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,1)); table.addCell(createCell("", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("產品訂購清單", textfont_H, Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,8)); table.addCell(createCell("序號", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,1)); table.addCell(createCell("產品信息", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,2,1)); table.addCell(createCell("規格型號", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,1)); table.addCell(createCell("單位", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,1)); table.addCell(createCell("單價", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,1)); table.addCell(createCell("數量", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,1)); table.addCell(createCell("小計", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,1)); table.addCell(createCell("1", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("塑料紙", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,2,1)); table.addCell(createCell("小號", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("個", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("20", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("20", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("400", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("2", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("塑料紙", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,2,1)); table.addCell(createCell("小號", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("個", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("20", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("20", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("400", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("3", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("塑料紙", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,2,1)); table.addCell(createCell("小號", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("個", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("20", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("20", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("400", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("4", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("合計", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,2,1)); table.addCell(createCell("", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("20", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("60", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("1200", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,1,1)); table.addCell(createCell("合計金額(元)", textfont_B,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,3,1)); table.addCell(createCell("壹仟倆佰元", textfont_B,Element.ALIGN_MIDDLE, Element.ALIGN_RIGHT,6,1)); table.addCell(createCell("顧客確認", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_CENTER,1,3)); table.addCell(createCell("注:本人已充分了解訂購產品的功能用途,是根據實際須要自願購買的。", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,8,1)); table.addCell(createCell("採購經辦人簽字:", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,6,1)); table.addCell(createCell("蓋章:", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,2,1)); table.addCell(createCell("簽字日期", textfont_H,Element.ALIGN_MIDDLE, Element.ALIGN_LEFT,8,1)); document.add(table); document.close(); } public static void main(String[] args) throws Exception { String filePath = FileStorageUtils.getTempPath(); File file = new File(filePath+"tee.pdf"); file.createNewFile(); new BasePDFWrite(file).generatePDF(); } }
三、路徑文件mongodb
package com.zdnst.common.utils; import com.mongodb.gridfs.GridFS; import com.mongodb.gridfs.GridFSDBFile; import com.mongodb.gridfs.GridFSInputFile; import com.zdnst.common.file.storage.FileStorage; import com.zdnst.common.file.storage.FileStorageFactory; import com.zdnst.common.infra.constants.BaseCode; import com.zdnst.common.infra.exception.ZdnstException; import com.zdnst.common.infra.mangodb.MongoDb; import com.zdnst.common.infra.utils.Assert; import com.zdnst.common.infra.utils.ConfigUtils; import com.zdnst.common.infra.utils.FileUtils; import com.zdnst.common.infra.utils.StringUtils; import org.apache.commons.io.FilenameUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.regex.Pattern; /** * 文件服務工具類 * Created by kaiqiang.wu on 2016/4/25. */ public class FileStorageUtils { private static Logger logger = LoggerFactory.getLogger(FileStorageUtils.class); /** * 獲取臨時文件存儲路徑 /${ClassPath}/files/ * @return * @throws Exception */ public static String getTempPath() throws Exception { // 獲取文件須要上傳到的路徑 String tempPath = ConfigUtils.getInstance().getClassPath() + "files/"; FileUtils.forceMkdir(new File(tempPath)); return tempPath; } /** * 獲得FileStorage實例 * @return */ public static FileStorage getFileStorage(){ String filestorageType = SystemProperties.getProperties().getProperty("filestorage.type"); String filestorageHome = SystemProperties.getProperties().getProperty("filestorage.home"); FileStorage fileStorage = FileStorageFactory.getInstance(filestorageType,filestorageHome).getFileStorage(); return fileStorage; } /** * 上傳文件到文件服務器 * @param srcPathFileName 本地文件路徑名 * @param destFileName 文件服務器存儲文件名 * @return * @throws Exception */ public static String uploadFile(String srcPathFileName, String destFileName) throws Exception{ try { Assert.notEmpty(srcPathFileName,"源文件不能爲空"); Assert.notEmpty(destFileName,"目標文件名不能爲空"); logger.info("上傳文件:{} --> {}", srcPathFileName, destFileName); FileStorage fileStorage = FileStorageUtils.getFileStorage(); String fileName = fileStorage.saveFile(srcPathFileName, destFileName); logger.info("上傳成功 {}", destFileName); return fileName; }catch (Exception e){ throw new Exception("上傳文件失敗:"+srcPathFileName+":"+e.getMessage(),e); } } /** * 判斷文件在文件服務器中是否存在 * @param fileName 文件名 * @return */ public static boolean exists(String fileName){ FileStorage fileStorage = FileStorageUtils.getFileStorage(); boolean exists = fileStorage.exists(fileName); return exists; } /** * 刪除文件 * @param fileName 文件名 * @return */ public static boolean delete(String fileName){ FileStorage fileStorage = FileStorageUtils.getFileStorage(); return fileStorage.delete(fileName); } /** * 縮放到指定大小 * @param fileName 原文件名 * @param toFileName 目標文件名 * @param width 目標寬 * @param height 目標高 * @return */ public static String scaleTo(String fileName,String toFileName,int width,int height){ FileStorage fileStorage = FileStorageUtils.getFileStorage(); return fileStorage.scaleTo(fileName,toFileName,width,height); } /** * 根據不一樣的縮放狀況處理縮放 * @param fileInfoDto * @return */ public static String scaleTo(FileInfoDto fileInfoDto){ String oriFileName = fileInfoDto.getOriFileName(); String toFileName = fileInfoDto.getFileName(); int oldWidth = fileInfoDto.getOriWidth(); int oldHeight = fileInfoDto.getOriHeight(); int newWidth = fileInfoDto.getScaleWidth(); int newHeight = fileInfoDto.getScaleHeight(); String ext = FilenameUtils.getExtension(oriFileName); FileStorage fileStorage = FileStorageUtils.getFileStorage(); logger.info("圖片縮放處理:{}",fileInfoDto); if(FileInfoDto.SCALE_BY_HEIGHT == fileInfoDto.getScaleType()){ // HEIGHT 表示目標圖片只進行高度限制,如:_HEIGHT_200x300;表示裁減後的規格300的高度,長度在保證原圖不變形狀況下可能會大於200,也可能小於200 // 原文件名: 6ABE5D72FAE4_640x320.jpg // 輸出文件名:6ABE5D72FAE4_640x320_HEIGHT_200x300.jpg //高度的縮放比 float scaleRate = Float.valueOf(newHeight) /Float.valueOf(oldHeight); logger.info("按高度進行縮放:{}",scaleRate); //高度不變時,須要對寬度進行的縮放計算獲得新的寬度 int scaleWith = (int)(oldWidth * scaleRate); //按高縮放後的名稱,與原要求名稱不一致 String scaleFileName = FilenameUtils.getBaseName(oriFileName)+"_HEIGHT_"+scaleWith+"x"+newHeight+"."+FilenameUtils.getExtension(oriFileName); if(!FileStorageUtils.exists(scaleFileName)){ logger.info("文件不存在,開始縮放:{}",scaleFileName); //判斷若是文件不存在,則進行處理 FileStorageUtils.scaleTo(oriFileName, scaleFileName, scaleWith, newHeight); }else{ logger.info("文件已存在,跳過縮放:{}",scaleFileName); } logger.info("按高度進行縮放成功:{}",scaleFileName); return scaleFileName; }else if(FileInfoDto.SCALE_BY_WIDTH == fileInfoDto.getScaleType()){ // WIDTH 表示目標圖片只進行寬限制,如:_WIDTH_200x300;表示裁減後的規格200的寬度,高度在保證原圖不變形狀況下可能會大於300,也可能小於300 // 原文件名: 6ABE5D72FAE4_640x320.jpg // 輸出文件名:6ABE5D72FAE4_640x320_WIDTH_200x300.jpg //寬度的縮放比 float scaleRate = Float.valueOf(newWidth) /Float.valueOf(oldWidth); logger.info("按寬度進行縮放:{}",scaleRate); //寬度不變時,須要對高度進行的縮放計算獲得新的高度 int scaleHeight = (int)(oldHeight * scaleRate); //按寬縮放後的名稱,與原要求名稱不一致 String scaleFileName = FilenameUtils.getBaseName(oriFileName)+"_WIDTH_"+newWidth+"x"+scaleHeight+"."+FilenameUtils.getExtension(oriFileName); if(!FileStorageUtils.exists(scaleFileName)){ logger.info("文件不存在,開始縮放:{}",scaleFileName); //判斷若是文件不存在,則進行處理 FileStorageUtils.scaleTo(oriFileName, scaleFileName, newWidth, scaleHeight); }else{ logger.info("文件已存在,跳過縮放:{}",scaleFileName); } logger.info("按寬度進行縮放成功:{}",scaleFileName); return scaleFileName; }else if(FileInfoDto.SCALE_BY_SIZE == fileInfoDto.getScaleType()){ //返回的圖片的寬和高要求與參數一致。 //若圖片寬和高大於要求值時,先縮小,再進裁剪 //若圖片寬或高小於要求值時,先放大,再進裁剪 String targetFileName = null; //要求的文件名去掉縮放值(80x100)後的前綴,如:11505E06-F876-48E0-93F7-95D218505DAE_288x220_TRUE String baseFileNamePrefix = toFileName.substring(0,toFileName.lastIndexOf("_")); //用於裁剪時以做中心裁剪 int afterScaleWidth = 0; int afterScaleHeight = 0; if(oldWidth >= newWidth && oldHeight >= newHeight){ //縮小 float scaleWidthRate = Float.valueOf(newWidth) /Float.valueOf(oldWidth); float scaleHeightRate = Float.valueOf(newHeight) /Float.valueOf(oldHeight); if(scaleWidthRate > scaleHeightRate){ //新舊比,寬比值大,表示較接近,剛以此邊做爲基準進行縮小 //寬度不變時,須要對高度進行的縮小計算獲得新的高度 int scaleHeight = (int)(oldHeight * scaleWidthRate); logger.info("按寬度進行縮小:{}",scaleWidthRate); //按寬縮放後的名稱,與原要求名稱不一致 targetFileName = baseFileNamePrefix+"_"+newWidth+"x"+scaleHeight+"."+ext; afterScaleWidth = newWidth; afterScaleHeight = scaleHeight; if(!FileStorageUtils.exists(targetFileName)){ logger.info("文件不存在,開始縮小:{}",targetFileName); //判斷若是文件不存在,則進行處理 FileStorageUtils.scaleTo(oriFileName, targetFileName, newWidth, scaleHeight); }else{ logger.info("文件已存在,跳過縮小:{}",targetFileName); } }else{ //按高縮小 int scaleWith = (int)(oldWidth * scaleHeightRate); logger.info("按高度進行縮小:{}",scaleHeightRate); //按高縮放後的名稱,與原要求名稱不一致 targetFileName = baseFileNamePrefix+"_"+scaleWith+"x"+newHeight+"."+ext; afterScaleWidth = scaleWith; afterScaleHeight = newHeight; if(!FileStorageUtils.exists(targetFileName)){ logger.info("文件不存在,開始縮小:{}",targetFileName); //判斷若是文件不存在,則進行處理 FileStorageUtils.scaleTo(oriFileName, targetFileName, scaleWith, newHeight); }else{ logger.info("文件已存在,跳過縮小:{}",targetFileName); } } }else{ //放大 float scaleWidthRate = Float.valueOf(newWidth) /Float.valueOf(oldWidth); float scaleHeightRate = Float.valueOf(newHeight) /Float.valueOf(oldHeight); if(scaleWidthRate > scaleHeightRate){ //按寬放大 //寬度不變時,須要對高度進行的縮放計算獲得新的高度 int scaleHeight = (int)(oldHeight * scaleWidthRate); logger.info("按寬度進行放大:{}",scaleWidthRate); //按寬縮放後的名稱,與原要求名稱不一致 targetFileName = baseFileNamePrefix+"_"+newWidth+"x"+scaleHeight+"."+ext; afterScaleWidth = newWidth; afterScaleHeight = scaleHeight; if(!FileStorageUtils.exists(targetFileName)){ logger.info("文件不存在,開始放大:{}",targetFileName); //判斷若是文件不存在,則進行處理 FileStorageUtils.scaleTo(oriFileName, targetFileName, newWidth, scaleHeight); }else{ logger.info("文件已存在,跳過放大:{}",targetFileName); } }else{ //按高放大 int scaleWith = (int)(oldWidth * scaleHeightRate); logger.info("按高度進行放大:{}",scaleHeightRate); //按高縮放後的名稱,與原要求名稱不一致 targetFileName = baseFileNamePrefix+"_"+scaleWith+"x"+newHeight+"."+ext; afterScaleWidth = scaleWith; afterScaleHeight = newHeight; if(!FileStorageUtils.exists(targetFileName)){ logger.info("文件不存在,開始放大:{}",targetFileName); //判斷若是文件不存在,則進行處理 FileStorageUtils.scaleTo(oriFileName, targetFileName, scaleWith, newHeight); }else{ logger.info("文件已存在,跳過放大:{}",targetFileName); } } } //對目標文件進行裁剪scaleFileName logger.info("裁剪:{} --> {}",targetFileName,toFileName); //中心裁剪 int x = (afterScaleWidth - newWidth) / 2; int y = (afterScaleHeight - newHeight) / 2 ; if(x < 0 || y < 0){ //計算異常時,不處理中心裁剪 x = 0; y = 0; } fileStorage.cutImg(targetFileName,toFileName,newWidth,newHeight,x,y); logger.info("裁剪成功:{}",toFileName); return toFileName; }else if(FileInfoDto.SCALE_BY_CENTER == fileInfoDto.getScaleType()){ //返回的圖片的寬和高要求與參數一致。直接縮放到指定的大小 logger.info("直接縮放到指定的大小:{}", toFileName); if(!FileStorageUtils.exists(toFileName)){ logger.info("文件不存在,開始縮放:{}",toFileName); FileStorageUtils.scaleTo(oriFileName, toFileName, newWidth, newHeight); }else{ logger.info("文件已存在,跳過縮放:{}",toFileName); } logger.info("縮放成功:{}",toFileName); return toFileName; }else{ throw new RuntimeException("not support scale type:"+fileInfoDto.getScaleType()); } } /** * 上傳文件到MongoDb或文件服務器 * @param srcPathFileName * @param destFileName * @param deleteBeforeUpload 上傳以前是否先執行刪除,MongoDb是上傳默認圖時使用 * @return * @throws Exception */ public static String uploadFileWithMongoDbOrFileServer(String srcPathFileName, String destFileName,boolean deleteBeforeUpload) throws Exception{ try { Assert.notEmpty(srcPathFileName,"源文件不能爲空"); Assert.notEmpty(destFileName,"目標文件名不能爲空"); String fileName = null; String fileStorageOpen = SystemProperties.getProperties().getProperty("filestorage.open"); if (StringUtils.COMMON_VALUE_1.equals(fileStorageOpen)) { //使用文件服務器進行存儲 //保存到文件服務器 --2016-04-25 by wkq fileName = FileStorageUtils.uploadFile(srcPathFileName, destFileName); }else if (StringUtils.COMMON_VALUE_2.equals(fileStorageOpen)) { //使用阿里OSS存儲 AliOssClient.getInstance().upload(srcPathFileName,destFileName); fileName = destFileName; } else { //使用原來的MongoDb存儲 logger.info("上傳文件MongoDb:{} --> {}", srcPathFileName, destFileName); GridFS gridFS = new GridFS(MongoDb.getInstance().getDb()); if(deleteBeforeUpload) { try { GridFSDBFile f = gridFS.findOne(destFileName); if (f != null) { gridFS.remove(destFileName); } } catch (IllegalArgumentException ex) { logger.error("delete from MongoDb,file not found"); } } File oriFile = new File(srcPathFileName); GridFSInputFile gfsFile = gridFS.createFile(oriFile); gfsFile.setFilename(destFileName); gfsFile.save(); fileName = destFileName; logger.info("上傳成功MongoDb {}", destFileName); } return fileName; }catch (Exception e){ throw new Exception("上傳文件失敗:"+srcPathFileName+":"+e.getMessage(),e); } } /** * 根據文件名解析獲得文件信息 * @param fileName 包含文件縮放信息的文件名 * @return */ public static FileInfoDto getFileInfo(String fileName){ try { //獲得原文件名 FileInfoDto fileInfoDto = new FileInfoDto(); fileInfoDto.setFileName(fileName); //解析獲得原文件名 String oriFileName = null;//原文件名 String prefixName = "";//原文件名前綴名 int first_ = fileName.indexOf("_"); int index_TRUE_ = fileName.indexOf("_TRUE_"); int index_HEIGHT_ = fileName.indexOf("_HEIGHT_"); int index_CENTER_ = fileName.indexOf("_CENTER_"); int index_WIDTH_ = fileName.indexOf("_WIDTH_"); int index_XING = fileName.indexOf("*"); String ext = FilenameUtils.getExtension(fileName);//png if (index_XING != -1 && first_ != -1) {// 11505E06-F876-48E0-93F7-95D218505DAE*288x220_TRUE_88x54.png prefixName = fileName.substring(0, first_);//11505E06-F876-48E0-93F7-95D218505DAE*288x220 } else if (index_TRUE_ != -1 || index_HEIGHT_ != -1 || index_WIDTH_ != -1 || index_CENTER_ != -1) { // 11505E06-F876-48E0-93F7-95D218505DAE_288x220_TRUE_88x54.png if (index_TRUE_ != -1) { prefixName = fileName.substring(0, index_TRUE_); } else if (index_HEIGHT_ != -1) { prefixName = fileName.substring(0, index_HEIGHT_); } else if (index_CENTER_ != -1) { prefixName = fileName.substring(0, index_CENTER_); } else if (index_WIDTH_ != -1) { prefixName = fileName.substring(0, index_WIDTH_); } } else if (first_ != -1) { //原文件 11505E06-F876-48E0-93F7-95D218505DAE_288x220.png //或有縮放 11505E06-F876-48E0-93F7-95D218505DAE_288x220_400x600.png String subFileName = fileName.substring(first_ + 1, fileName.length()); if (subFileName.indexOf("_") != -1) { //有縮放 11505E06-F876-48E0-93F7-95D218505DAE_288x220_400x600.png prefixName = fileName.substring(0, fileName.lastIndexOf("_")); fileInfoDto.setScaleType(FileInfoDto.SCALE_BY_SIZE); } else { //無縮放 prefixName = FilenameUtils.getBaseName(fileName); fileInfoDto.setScaleType(FileInfoDto.NO_SCALE); } } else { //原文件名,無縮放,無大小劃線 prefixName = FilenameUtils.getBaseName(fileName); } oriFileName = prefixName + "." + ext;//11505E06-F876-48E0-93F7-95D218505DAE*288x220.png fileInfoDto.setOriFileName(oriFileName); fileInfoDto.setExt(ext); //處理縮放 fileInfoDto.setScaleType(FileInfoDto.NO_SCALE);//默認無縮放 String oriSizeStr = ""; if (index_XING != -1) { oriSizeStr = fileName.substring(index_XING + 1, first_); } else { String subFileName = fileName.substring(first_ + 1, fileName.length()); if (subFileName.indexOf("_") != -1) { oriSizeStr = subFileName.substring(0, subFileName.indexOf("_")); } } String[] oldSizes = oriSizeStr.split("x"); if (oldSizes != null && oldSizes.length > 1 && isNum(oldSizes[0], oldSizes[1])) { int oriWidth = Integer.parseInt(oldSizes[0]); //原圖寬 int oriHeight = Integer.parseInt(oldSizes[1]); //原圖高 fileInfoDto.setOriWidth(oriWidth); fileInfoDto.setOriHeight(oriHeight); //縮放的尺寸 String newSizeStr = fileName.substring(fileName.lastIndexOf("_") + 1, fileName.lastIndexOf("."));//縮放要求的尺寸 String[] newSizes = newSizeStr.split("x"); if (newSizes != null && newSizes.length > 1 && isNum(newSizes[0], newSizes[1])) { int newWidth = Integer.parseInt(newSizes[0]); int newHeight = Integer.parseInt(newSizes[1]); fileInfoDto.setScaleWidth(newWidth); fileInfoDto.setScaleHeight(newHeight); //只有正確獲得尺寸纔是縮放 if (index_TRUE_ != -1) { fileInfoDto.setScaleType(FileInfoDto.SCALE_BY_SIZE); } else if (index_HEIGHT_ != -1) { fileInfoDto.setScaleType(FileInfoDto.SCALE_BY_HEIGHT); } else if (index_CENTER_ != -1) { fileInfoDto.setScaleType(FileInfoDto.SCALE_BY_CENTER); } else if (index_WIDTH_ != -1) { fileInfoDto.setScaleType(FileInfoDto.SCALE_BY_WIDTH); } else { fileInfoDto.setScaleType(FileInfoDto.SCALE_BY_SIZE); } } } return fileInfoDto; }catch (Exception e){ throw new ZdnstException(BaseCode.ERROR_CODE112,"請求文件名解析異常:"+e.getMessage(),e); } } /** * 長度是否都是數字格式 * @param w * @param h * @return */ private static boolean isNum(String w,String h){ Pattern pattern = Pattern.compile("[0-9]*"); boolean isNum = pattern.matcher(w).matches()&&pattern.matcher(h).matches(); //都是數字 return isNum; } }
package com.zdnst.common.infra.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Properties; /** * 系統配置文件 */ public class ConfigUtils { private static Logger logger = LoggerFactory.getLogger(ConfigUtils.class); // 應用根目錄 private String rootPath = null; // classes目錄 private String classPath = null; private static ConfigUtils instance = new ConfigUtils(); private ConfigUtils() { logger.info("OS NAME:{}", System.getProperty("os.name")); URL url = this.getClass().getClassLoader().getResource("/"); if (url == null) { url = ConfigUtils.class.getResource("/"); } classPath = url.getFile(); if (System.getProperty("os.name") != null && System.getProperty("os.name").toUpperCase().indexOf("WINDOWS") != -1 && classPath.startsWith("/")) { classPath = classPath.substring(1); } classPath = classPath.replace("%20", " "); rootPath = classPath.replace("/WEB-INF/classes/", ""); rootPath = rootPath.replace("%20", " "); logger.info("classPath:" + classPath); logger.info("rootPath:" + rootPath); } /** * 取惟一的cfg實例 * * @return 惟一的cfg實例 */ public static synchronized ConfigUtils getInstance() { return instance; } /** * 工具方法,讀取Properties配置文件 * * @param propPath properties配置文件絕對路徑 * @return Properties */ public static Properties loadProperties(String propPath) { Properties properties = new Properties(); InputStream inputStream = null; try { inputStream = new FileInputStream(new File(propPath)); properties.load(inputStream); } catch (IOException e) { logger.error("load properties error." + propPath, e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { logger.warn("load properties error:" + e.getMessage()); } } } return properties; } /** * 獲取應用根目錄(網站根目錄,如d:\MyApp) * * @return */ public String getRoot() { return rootPath; } /** * 取WEB-INF絕對路徑 * * @return WEB-INF絕對路徑目錄(eg:/X:/XXX//WEB-INF/) */ public String getWebInf() { if (classPath.indexOf("WEB-INF") != -1) { return getRoot() + "/WEB-INF/"; } else { logger.warn("no WEB-INF path in current environment. return the root path instead."); return getRoot(); } } /** * 取類的運行根目錄的絕對路徑 * * @return classes絕對路徑目錄(eg:在web環境中返回/X:/XXX//WEB-INF/classes/) */ public String getClassPath() { return classPath; } public static void main(String[] args) { System.out.println(ConfigUtils.getInstance().getRoot()); System.out.println(ConfigUtils.getInstance().getWebInf()); } }