admin 管理员组

文章数量: 1087652

aspose上传,预览,下载,删除文件

介绍:

这里的文件服务器地址为oss地址,相关配置不放出来了。使用aspose实现了上传,预览,下载,删除等功能。
测试
上传

下载

预览
预览提供两种方式,一种是转换流文件,一种是将word,ppt,xls等文件转换为可以预览的pdf文件重新上传到文件服务器返回可以预览的地址。
1.返回流文件

2.返回预览地址

删除
删除直接将文件地址传进去就行了

依赖文件
这里依赖jar包提供两种方式:
1.pom文件方式

<!--        aspose依赖--><dependency><groupId>com.aspose</groupId><artifactId>aspose-slides</artifactId><version>15.9.0</version></dependency><dependency><groupId>com.aspose</groupId><artifactId>aspose-cells</artifactId><version>8.5.2</version></dependency><dependency><groupId>com.aspose</groupId><artifactId>aspose-words</artifactId><version>16.8.0-jdk16</version></dependency>

**!注意:**这里可能无法从往上拉取jar包,提供mvn命令加载方式:

mvn install:install-file
-Dfile=D:/mavenStore/aspose.slides-15.9.0.jar
-DgroupId=com.aspose
-DartifactId=aspose-slides
-Dversion=15.9.0
-Dpackaging=jarmvn install:install-file
-Dfile=D:/mavenStore/aspose-cells-8.5.2.jar
-DgroupId=com.aspose
-DartifactId=aspose-cells
-Dversion=8.5.2
-Dpackaging=jarmvn install:install-file
-Dfile=D:/mavenStore/aspose-words-16.8.0-jdk16.jar
-DgroupId=com.aspose
-DartifactId=aspose-words
-Dversion=16.8.0-jdk16
-Dpackaging=jar

2.外部jar包方式

   <!--aspose办公软件处理依赖--><dependency><groupId>com.aspose</groupId><artifactId>aspose-slides</artifactId><version>15.9.0</version><scope>system</scope><systemPath>${project.basedir}/src/main/resources/lib/aspose.slides-15.9.0.jar</systemPath></dependency><dependency><groupId>com.aspose</groupId><artifactId>aspose-cells</artifactId><version>8.5.2</version><scope>system</scope><systemPath>${project.basedir}/src/main/resources/lib/aspose-cells-8.5.2.jar</systemPath></dependency><dependency><groupId>com.aspose</groupId><artifactId>aspose-words</artifactId><version>16.8.0-jdk16</version><scope>system</scope><systemPath>${project.basedir}/src/main/resources/lib/aspose-words-16.8.0-jdk16.jar</systemPath></dependency><!--file转MultipartFile--><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency>
<!--    配置打包外部jar--><build><plugins><!--解决java.lang.NoClassDefFoundError: com/aspose/words/License--><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><!--设置为true,以便把本地的system的jar也包括进来--><includeSystemScope>true</includeSystemScope></configuration></plugin></plugins></build>

相关sql

create table dj_pdf_address
(file_id     bigint auto_increment comment '生成pdf id主键',file_name   varchar(255) not null comment '文件名称 不带后缀',source_path text         not null comment '源文件地址:转换之前的地址(word,ppt,excel)',target_path text         not null comment 'pdf文件地址 转换后新的文件地址',create_time datetime     null comment '创建时间',constraint dj_pdf_address_file_id_uindexunique (file_id)
)comment 'word,ppt,excel 转换pdf存储表';alter table dj_pdf_addressadd primary key (file_id);

代码实现
1.controler

@Api(tags = "文件管理")
@RestController
@RequestMapping("/file/")
@Slf4j
public class FileController {@Resourceprivate OssFileService ossFileService;@Resourceprivate PdfAddressService pdfAddressService;@PostMapping("upload")@ApiOperation("文件上传")public AjaxResult upload(@RequestParam MultipartFile file){log.info("进入common upload方法");try {// 上传并返回访问地址String url = ossFileService.uploadFile(file, FileTypeConstants.COMMON);OssFile ossFile = new OssFile();ossFile.setName(file.getOriginalFilename());ossFile.setUrl(url);ossFile.setSize(file.getSize());ossFile.setType(file.getContentType());return AjaxResult.success(ossFile);} catch (Exception e) {log.error("上传文件失败", e);return AjaxResult.error(HttpStatus.ERROR,e.getMessage());}}@PostMapping("downloadPolicyFile")@ApiOperation("文件下载")public void downloadRotPolicy(@RequestBody DownloadFileReq downloadFileReq, HttpServletResponse response) throws Exception {ossFileService.downloadPolicyFile(downloadFileReq,response);}@PostMapping("rotPolicyFile")@ApiOperation("txt文件预览")public void rotPolicyFile(@RequestBody DownloadFileReq downloadFileReq, HttpServletResponse response) throws Exception {ossFileService.rotPolicyFile(downloadFileReq,response);}//暂时不调@PostMapping("wordPolityFile")@ApiOperation("word,ppt,excel文件预览")public R<?> wordPolityFile(@RequestBody @Validated WordFileReq wordFileReq) throws Exception {return R.ok(pdfAddressService.wordPolityFile(wordFileReq));}@PostMapping("remove")@ApiOperation("删除文件")public void removeFile(@Validated @RequestBody RemoveFileReq removeFileReq){ossFileService.removeFile(removeFileReq.getFileUrl());}
}

service

public interface OssFileService{/*** 文件上传接口* * @param file 上传的文件* @return 访问地址* @throws Exception*/public String uploadFile(MultipartFile file,String type) throws Exception;void downloadPolicyFile(DownloadFileReq downloadFileReq, HttpServletResponse response) throws IOException;void rotPolicyFile(DownloadFileReq downloadFileReq, HttpServletResponse response) throws Exception;void removeFile(String fileUrl);
}
public interface PdfAddressService extends IService<PdfAddress> {String wordPolityFile(WordFileReq wordFileReq) throws Exception;
}

bean

*** word,ppt,excel 转换pdf存储表* @TableName dj_pdf_address*/
@TableName(value ="dj_pdf_address")
@Data
public class PdfAddress implements Serializable {/*** 生成pdf id主键*/@TableId(value = "file_id", type = IdType.AUTO)private Long fileId;/*** 文件名称 不带后缀*/@TableField(value = "file_name")private String fileName;/*** 源文件地址:转换之前的地址(word,ppt,excel)*/@TableField(value = "source_path")private String sourcePath;/*** pdf文件地址 转换后新的文件地址*/@TableField(value = "target_path")private String targetPath;/*** 创建时间*/@TableField(value = "create_time")private Date createTime;@TableField(exist = false)private static final long serialVersionUID = 1L;
}```

req

@Data
@ApiModel("下载文件请求参数")
public class DownloadFileReq {@ApiModelProperty("源文件地址")private String urlPath;}

@Data
@ApiModel("word,excel,ppt预览参数")
public class WordFileReq extends DownloadFileReq{@ApiModelProperty(notes = "study:资料;common:通用")@NotBlank(message = "文件预览参数不能为空")private String fileType;

impl

@Slf4j
@Primary
@Service
public class OssFileServiceImpl implements OssFileService {@Resourceprivate OssConfig ossConfig;/*** 上传文件** @param file file* @return 返回对象存储的url* @throws Exception Exception*/@Overridepublic String uploadFile(MultipartFile file,String type) throws Exception {try {int fileNameLength = Objects.requireNonNull(file.getOriginalFilename()).length();//默认的文件名最大长度 100if (fileNameLength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);}//默认允许上传的文件格式FileUploadUtils.assertAllowed(file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);InputStream inputStream = file.getInputStream();String originalFileName = file.getOriginalFilename();String uuid = UUID.randomUUID().toString().replaceAll("-", "");originalFileName = uuid + "/" + originalFileName;String datePath = new DateTime().toString("yyyy/MM/dd");//文件名originalFileName = ossConfig.getFolder() + "/" +type+"/"+ datePath + "/" + originalFileName;//OSS对象上传OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());ossClient.putObject(ossConfig.getBucketName(), originalFileName, inputStream);ossClient.shutdown();return  "https://" + ossConfig.getBucketName() + "." + ossConfig.getEndpoint()+ "/" + originalFileName;} catch (Exception e) {throw new IOException(e.getMessage(), e);}}/*** 下载* @param downloadFileReq downloadFileReq* @param response response* @throws IOException IOException*/@Overridepublic void downloadPolicyFile(DownloadFileReq downloadFileReq, HttpServletResponse response) throws IOException {checkUrl(downloadFileReq.getUrlPath());String urlPath=downloadFileReq.getUrlPath();String suffix=urlPath.substring(urlPath.lastIndexOf(".")+GenParamsConstants.ONE);String tempThreeSuffix="pdf,PDF,jpg,JPG,png,PNG,txt,TXT,rar,zip,RAR,ZIP,doc,DOC,ppt,PPT,XLS,xls";String tempFourSuffix="jpeg,JPEG,XLSX,xlsx,PPTX,pptx,docx,DOCX";String newFileName=null;if (StringUtils.isNotBlank(suffix)){if (tempThreeSuffix.contains(suffix)){newFileName = urlPath.substring(urlPath.lastIndexOf(ossConfig.getFolder()),urlPath.lastIndexOf(".") + GenParamsConstants.FOUR);}else if (tempFourSuffix.contains(suffix)){newFileName = urlPath.substring(urlPath.lastIndexOf(ossConfig.getFolder()),urlPath.lastIndexOf(".") + GenParamsConstants.FIVE);}}downloadPolicy(urlPath,newFileName,response);}/*** txt预览* @param downloadFileReq downloadFileReq* @param response response* @throws IOException IOException*/@Overridepublic void rotPolicyFile(DownloadFileReq downloadFileReq, HttpServletResponse response) throws Exception {//判断文件地址是否为空checkUrl(downloadFileReq.getUrlPath());String urlPath=downloadFileReq.getUrlPath();String suffix=urlPath.substring(urlPath.lastIndexOf(".")+GenParamsConstants.ONE);String tempSuffix="pdf,PDF,xls,xlsx,doc,docx,ppt,pptx,txt,TXT";if (!tempSuffix.contains(suffix)) throw new ServiceException("文档类型"+suffix+"不支持预览!");policyRots(urlPath,response);}/*** 通过url 删除文件* @param fileUrl fileUrl*/@Overridepublic void removeFile(String fileUrl) {OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());String newFileName = fileUrl.substring(fileUrl.lastIndexOf(ossConfig.getFolder()), fileUrl.lastIndexOf(".") + 5);boolean flag = ossClient.doesObjectExist(ossConfig.getBucketName(), newFileName);if (flag){ossClient.deleteObject(ossConfig.getBucketName(), newFileName);ossClient.shutdown();}else{throw new ServiceException("源文件不存在,删除失败!",HttpStatus.MOVED_PERM);}}/*** 路径校验* @param url url*/public void checkUrl(String url){if (StringUtils.isBlank(url)) //throw new ServiceException("下载或预览文件路径不能为空",HttpStatus.PARAMETER_INVALID);}/*** 下载文件* @param url url* @param response response* @throws IOException IOException*/private void downloadPolicy(String url,String fileName, HttpServletResponse response) throws IOException {OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());OSSObject ossObject = ossClient.getObject(ossConfig.getBucketName(), fileName);int i = fileName.lastIndexOf("/");BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());response.setContentType("application/octet-stream;charset=utf-8");response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName.substring(i + 1), "utf-8"));response.addHeader("Pargam", "no-cache");response.addHeader("Cache-Control", "no-cache");BufferedInputStream bufferedInputStream = null;try {bufferedInputStream = new BufferedInputStream(ossObject.getObjectContent());byte[] car = new byte[1024];int length;while ((length = bufferedInputStream.read(car)) != -1) {out.write(car, 0, length);}} catch (FileException e) {e.getMessage();log.error("文件下载异常:{}", e.getMessage());} finally {out.flush();out.close();assert bufferedInputStream != null;bufferedInputStream.close();ossClient.shutdown();}}/*** word 转pdf 预览* @param url      url* @param response response* @throws Exception Exception*/private void policyRots(String url, HttpServletResponse response) throws Exception {if (StringUtils.isBlank(url)) {throw new ServiceException("文件为空,不能预览");}File file;String suffix = url.substring(url.lastIndexOf(".") + GenParamsConstants.ONE);switch (suffix) {case "PDF":case "pdf": {HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();httpUrl.connect();file = PdfUtils.inputStreamToFile(httpUrl.getInputStream(), UUID.randomUUID().toString() + ".pdf");response.setContentType("application/pdf");break;}case "TXT":case "txt": {HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();httpUrl.connect();file = PdfUtils.inputStreamToFile(httpUrl.getInputStream(), UUID.randomUUID().toString() + ".txt");response.setContentType("text/html;charset=utf-8");break;}case "doc":case "docx":file = new File(Objects.requireNonNull(PdfUtils.word2pdf(url, createTempPath() + UUID.randomUUID().toString() + ".pdf")));response.setContentType("application/pdf");break;case "xls":case "xlsx":file = new File(Objects.requireNonNull(PdfUtils.excel2pdf(url, createTempPath() + UUID.randomUUID().toString() + ".pdf")));response.setContentType("application/pdf");break;case "ppt":case "pptx":file = new File(Objects.requireNonNull(PdfUtils.ppt2pdf(url, createTempPath() + UUID.randomUUID().toString() + ".pdf")));response.setContentType("application/pdf");break;default:throw new RuntimeException("文件格式不支持!");}InputStream stream = null;ServletOutputStream outputStream = null;try {response.setCharacterEncoding("UTF-8");stream = new FileInputStream(file);outputStream = response.getOutputStream();byte[] buff = new byte[1024];int length;while ((length = stream.read(buff)) > GenParamsConstants.ZERO) {outputStream.write(buff, 0, length);}} catch (IOException e) {e.printStackTrace();log.error(e.getMessage());} finally {assert stream != null;stream.close();assert outputStream != null;outputStream.close();outputStream.flush();}}public static FileItem createFileItem(File file) {FileItemFactory factory = new DiskFileItemFactory(16, null);FileItem item = factory.createItem("textField", "text/plain", true, file.getName());int bytesRead = 0;byte[] buffer = new byte[8192];try {FileInputStream fis = new FileInputStream(file);OutputStream os = item.getOutputStream();while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {os.write(buffer, 0, bytesRead);}os.close();fis.close();} catch (IOException e) {e.printStackTrace();}return item;}/*** 处理文件后缀* @param filename 文件名称* @return 不带文件后缀的名称*/public static String getFileNameNoEx(String filename) {if ((filename != null) && (filename.length() > 0)) {int dot = filename.lastIndexOf('.');if ((dot > -1) && (dot < (filename.length()))) {return filename.substring(0, dot);}}return filename;}/*** 在当前项目目录下创建临时文件目录* @return tempFilePath*/public static String createTempPath(){String tempPath=System.getProperty("user.dir");File file=new File(tempPath+"/temp");if (!file.exists()){file.mkdir();}return file.getPath()+"/";}
}
Slf4j
@Service
public class PdfAddressServiceImpl extends ServiceImpl<PdfAddressMapper, PdfAddress>implements PdfAddressService {String tempPath=System.getProperty("user.dir")+"/temp";@Resourceprivate OssFileServiceImpl ossFileService;@Resourceprivate PdfAddressMapper pdfAddressMapper;/*** word,ppt,excel 预览* 这里返回可以访问的pdf路径* @param wordFileReq wordFileReq* @return pefPath*/@Overridepublic String wordPolityFile(WordFileReq wordFileReq) throws Exception {//校验urlossFileService.checkUrl(wordFileReq.getUrlPath());//根据源路径查询是否存在pdf路径,存在直接返回;没有处理入库之后返回PdfAddress tempPdfAddress=pdfAddressMapper.selectOne(new LambdaQueryWrapper<PdfAddress>() //.eq(PdfAddress::getSourcePath,wordFileReq.getUrlPath()));String pdfPath;if (ObjectUtil.isNotEmpty(tempPdfAddress)){pdfPath=tempPdfAddress.getTargetPath();}else {String urlPath=wordFileReq.getUrlPath();String suffix=urlPath.substring(urlPath.lastIndexOf(".")+ GenParamsConstants.ONE);String tempSuffix="xls,xlsx,doc,docx,ppt,pptx";if (!tempSuffix.contains(suffix)) throw new ServiceException("非word,ppt,excel文件类型不支持预览!");File file;String fileName;switch (suffix){case "doc":case "docx":String  docFileName= StringUtils.substringAfterLast(urlPath,"/");fileName= OssFileServiceImpl.getFileNameNoEx(docFileName);//生成临时文件file = new File(Objects.requireNonNull(PdfUtils.word2pdf(urlPath, //OssFileServiceImpl.createTempPath() + fileName + ".pdf")));//file转MultipartFileFileItem docFileItem = OssFileServiceImpl.createFileItem(file);MultipartFile docMultipartFile=new CommonsMultipartFile(docFileItem);// 文件上传到服务器pdfPath=ossFileService.uploadFile(docMultipartFile,wordFileReq.getFileType());// 新增到dj_pdf_addressint docCount=insertPdfAddress(fileName,wordFileReq.getUrlPath(),pdfPath);//删除临时文件if (docCount>0){String  docPdfName= StringUtils.substringAfterLast(pdfPath,"/");log.info("开始删除临时文件:{}----{}",docPdfName,new Date());removeTempFile(tempPath,docPdfName);}break;case "xls":case "xlsx":String excelFileName=StringUtils.substringAfterLast(urlPath,"/");fileName= OssFileServiceImpl.getFileNameNoEx(excelFileName);file = new File(Objects.requireNonNull(PdfUtils.excel2pdf(urlPath, //OssFileServiceImpl.createTempPath() + fileName + ".pdf")));//file转MultipartFileFileItem excelFileItem = OssFileServiceImpl.createFileItem(file);MultipartFile excelMultipartFile=new CommonsMultipartFile(excelFileItem);// 文件上传到服务器pdfPath=ossFileService.uploadFile(excelMultipartFile,wordFileReq.getFileType());// 新增到dj_pdf_addressint excelCount=insertPdfAddress(fileName,wordFileReq.getUrlPath(),pdfPath);//删除临时文件if (excelCount>0){String  excelPdfName= StringUtils.substringAfterLast(pdfPath,"/");log.info("开始删除临时文件:{}----{}",excelPdfName,new Date());removeTempFile(tempPath,excelPdfName);}break;case "ppt":case "pptx":String pptFileName=StringUtils.substringAfterLast(urlPath,"/");fileName= OssFileServiceImpl.getFileNameNoEx(pptFileName);file = new File(Objects.requireNonNull(PdfUtils.ppt2pdf(urlPath, //OssFileServiceImpl.createTempPath() + fileName + ".pdf")));FileItem pptFileItem = OssFileServiceImpl.createFileItem(file);MultipartFile pptMultipartFile=new CommonsMultipartFile(pptFileItem);// 文件上传到服务器pdfPath=ossFileService.uploadFile(pptMultipartFile,wordFileReq.getFileType());// 新增到dj_pdf_addressint pptCount=insertPdfAddress(fileName,wordFileReq.getUrlPath(),pdfPath);//删除临时文件if (pptCount>0){String  pptPdfName= StringUtils.substringAfterLast(pdfPath,"/");log.info("开始删除临时文件:{}----{}",pptPdfName,new Date());removeTempFile(tempPath,pptPdfName);}break;default:throw new RuntimeException("文件格式不支持!");}}return pdfPath;}/*** 新增paf数据库*/private int insertPdfAddress(String name,String sourcePath,String targetPath){PdfAddress pdfAddress=new PdfAddress();pdfAddress.setFileName(name);pdfAddress.setSourcePath(sourcePath);pdfAddress.setTargetPath(targetPath);pdfAddress.setCreateTime(new Date());return pdfAddressMapper.insert(pdfAddress);}//删除临时文件private static void removeTempFile(String dirPath,String fileName) {File file = new File(dirPath);boolean flag=false;if (file.isDirectory()) {String[] dirPathList = file.list();//遍历文件for (int i = 0; i < Objects.requireNonNull(dirPathList).length; i++) {String filePath = dirPath + File.separator + dirPathList[i];File fileDelete = new File(filePath);//校验删除文件if (fileDelete.getName().equals(fileName)) {flag=fileDelete.delete();break;}}}if (!flag){log.error("删除临时文件:{}异常---{}",fileName,new Date());}}
}

utils

public class FileUploadUtils
{/*** 默认大小 50M*/public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;/*** 默认的文件名最大长度 100*/public static final int DEFAULT_FILE_NAME_LENGTH = 100;/*** 默认上传的地址*/private static String defaultBaseDir = YsgzConfig.getProfile();public static void setDefaultBaseDir(String defaultBaseDir){FileUploadUtils.defaultBaseDir = defaultBaseDir;}public static String getDefaultBaseDir(){return defaultBaseDir;}/*** 以默认配置进行文件上传** @param file 上传的文件* @return 文件名称* @throws Exception*/public static final String upload(MultipartFile file) throws IOException{try{return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);}catch (Exception e){throw new IOException(e.getMessage(), e);}}/*** 根据文件路径上传** @param baseDir 相对应用的基目录* @param file 上传的文件* @return 文件名称* @throws IOException*/public static final String upload(String baseDir, MultipartFile file) throws IOException{try{return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);}catch (Exception e){throw new IOException(e.getMessage(), e);}}/*** 文件上传** @param baseDir 相对应用的基目录* @param file 上传的文件* @param allowedExtension 上传文件类型* @return 返回上传成功的文件名* @throws FileSizeLimitExceededException 如果超出最大大小* @throws FileNameLengthLimitExceededException 文件名太长* @throws IOException 比如读写文件出错时* @throws InvalidExtensionException 文件校验异常*/public static final String upload(String baseDir, MultipartFile file, String[] allowedExtension)throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,InvalidExtensionException{int fileNamelength = Objects.requireNonNull(file.getOriginalFilename()).length();if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH){throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);}assertAllowed(file, allowedExtension);String fileName = extractFilename(file);String absPath = getAbsoluteFile(baseDir, fileName).getAbsolutePath();file.transferTo(Paths.get(absPath));return getPathFileName(baseDir, fileName);}/*** 编码文件名*/public static final String extractFilename(MultipartFile file){return StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(),FilenameUtils.getBaseName(file.getOriginalFilename()), Seq.getId(Seq.uploadSeqType), getExtension(file));}public static final File getAbsoluteFile(String uploadDir, String fileName) throws IOException{File desc = new File(uploadDir + File.separator + fileName);if (!desc.exists()){if (!desc.getParentFile().exists()){desc.getParentFile().mkdirs();}}return desc;}public static final String getPathFileName(String uploadDir, String fileName) throws IOException{int dirLastIndex = YsgzConfig.getProfile().length() + 1;String currentDir = StringUtils.substring(uploadDir, dirLastIndex);return Constants.RESOURCE_PREFIX + "/" + currentDir + "/" + fileName;}/*** 文件大小校验** @param file 上传的文件* @return* @throws FileSizeLimitExceededException 如果超出最大大小* @throws InvalidExtensionException*/public static final void assertAllowed(MultipartFile file, String[] allowedExtension)throws FileSizeLimitExceededException, InvalidExtensionException{long size = file.getSize();if (size > DEFAULT_MAX_SIZE){throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);}String fileName = file.getOriginalFilename();String extension = getExtension(file);if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)){if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION){throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,fileName);}else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION){throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,fileName);}else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION){throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,fileName);}else if (allowedExtension == MimeTypeUtils.VIDEO_EXTENSION){throw new InvalidExtensionException.InvalidVideoExtensionException(allowedExtension, extension,fileName);}else{throw new InvalidExtensionException(allowedExtension, extension, fileName);}}}/*** 判断MIME类型是否是允许的MIME类型** @param extension* @param allowedExtension* @return*/public static final boolean isAllowedExtension(String extension, String[] allowedExtension){for (String str : allowedExtension){if (str.equalsIgnoreCase(extension)){return true;}}return false;}/*** 获取文件名的后缀** @param file 表单文件* @return 后缀名*/public static final String getExtension(MultipartFile file){String extension = FilenameUtils.getExtension(file.getOriginalFilename());if (StringUtils.isEmpty(extension)){extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));}return extension;}
}
public class MimeTypeUtils
{public static final String IMAGE_PNG = "image/png";public static final String IMAGE_JPG = "image/jpg";public static final String IMAGE_JPEG = "image/jpeg";public static final String IMAGE_BMP = "image/bmp";public static final String IMAGE_GIF = "image/gif";public static final String[] IMAGE_EXTENSION = { "bmp", "gif", "jpg", "jpeg", "png" };public static final String[] FLASH_EXTENSION = { "swf", "flv" };public static final String[] MEDIA_EXTENSION = { "swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg","asf", "rm", "rmvb" };public static final String[] VIDEO_EXTENSION = { "mp4", "avi", "rmvb" };public static final String[] DEFAULT_ALLOWED_EXTENSION = {// 图片"bmp", "gif", "jpg", "jpeg", "png",// word excel powerpoint"doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt",// 压缩文件"rar", "zip", "gz", "bz2",// 视频格式"mp4", "avi", "rmvb",// pdf"pdf" };public static String getExtension(String prefix){switch (prefix){case IMAGE_PNG:return "png";case IMAGE_JPG:return "jpg";case IMAGE_JPEG:return "jpeg";case IMAGE_BMP:return "bmp";case IMAGE_GIF:return "gif";default:return "";}}
}
@Slf4j
public class PdfUtils {/*** word 转为 pdf 输出** @param inPath  word文件* @param outPath pdf 输出文件目录*/public static String word2pdf(String inPath, String outPath) {// 验证Licenseif (AsposeLicenseUtils.setWordsLicense()){long start=System.currentTimeMillis();FileOutputStream os = null;try {String path = outPath.substring(0, outPath.lastIndexOf(File.separator));File file = new File(path);// 创建文件夹if (!file.exists()) {file.mkdirs();}// 新建一个空白pdf文档file = new File(outPath);os = new FileOutputStream(file);// Address是将要被转化的word文档Document doc = new Document(inPath);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,doc.save(os, com.aspose.words.SaveFormat.PDF);long end=System.currentTimeMillis();log.info("word转pdf耗时:"+(end-start)/1000.0+":秒");os.close();} catch (Exception e) {if (os != null) {try {os.close();} catch (IOException e1) {e1.printStackTrace();}}e.printStackTrace();}}return outPath;}/*** excel 转为 pdf 输出** @param inPath  excel 文件* @param outPath pdf 输出文件目录*/public static String excel2pdf(String inPath, String outPath) {// 验证Licenseif (AsposeLicenseUtils.setWordsLicense()){long start=System.currentTimeMillis();FileOutputStream os = null;try {String path = outPath.substring(0, outPath.lastIndexOf(File.separator));File file = new File(path);// 创建文件夹if (!file.exists()) {file.mkdirs();}// 新建一个空白pdf文档file = new File(outPath);os = new FileOutputStream(file);// Address是将要被转化的excel表格Workbook workbook = new Workbook(new FileInputStream(getFile(inPath)));workbook.save(os, com.aspose.cells.SaveFormat.PDF);long end=System.currentTimeMillis();log.info("excel转pdf耗时:"+(end-start)/1000.0+":秒");os.close();} catch (Exception e) {if (os != null) {try {os.close();} catch (IOException e1) {e1.printStackTrace();}}e.printStackTrace();}}return outPath;}/*** ppt 转为 pdf 输出** @param inPath  ppt 文件* @param outPath pdf 输出文件目录*/public static String ppt2pdf(String inPath, String outPath) {// 验证Licenseif (AsposeLicenseUtils.setWordsLicense()){long start=System.currentTimeMillis();FileOutputStream os = null;try {String path = outPath.substring(0, outPath.lastIndexOf(File.separator));File file = new File(path);// 创建文件夹if (!file.exists()) {file.mkdirs();}// 新建一个空白pdf文档file = new File(outPath);os = new FileOutputStream(file);// Address是将要被转化的PPT幻灯片Presentation pres = new Presentation(new FileInputStream(getFile(inPath)));pres.save(os, com.aspose.slides.SaveFormat.Pdf);long end=System.currentTimeMillis();log.info("ppt转pdf耗时:"+(end-start)/1000.0+":秒");os.close();} catch (Exception e) {if (os != null) {try {os.close();} catch (IOException e1) {e1.printStackTrace();}}e.printStackTrace();}}return outPath;}/*** OutputStream 转 InputStream*/public static ByteArrayInputStream parse(OutputStream out) {ByteArrayOutputStream byteArrayOutputStream = (ByteArrayOutputStream) out;return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());}/*** InputStream 转 File*/public static File inputStreamToFile(InputStream ins, String name) throws Exception {File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);if (file.exists()) {return file;}OutputStream os =null;try {os = new FileOutputStream(file);int bytesRead;int len = 8192;byte[] buffer = new byte[len];while ((bytesRead = ins.read(buffer, 0, len)) != -1) {os.write(buffer, 0, bytesRead);}}catch (Exception e){e.printStackTrace();log.error(e.getMessage());}finally {assert os != null;os.close();ins.close();}return file;}/*** 根据网络地址获取 File 对象*/public static File getFile(String url) throws Exception {String suffix = url.substring(url.lastIndexOf("."));HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();httpUrl.connect();return PdfUtils.inputStreamToFile(httpUrl.getInputStream(), UUID.randomUUID().toString() + suffix);}}
@Slf4j
public class AsposeLicenseUtils {private static License license=new License();/***获取License的输入流*@return InputStream*/private static InputStream getLicenseInput(){InputStream inputStream=null;ClassLoader contextClassLoader=Thread.currentThread().getContextClassLoader();try{//获取项目resource下的文件流inputStream=contextClassLoader.getResourceAsStream("license.xml");}catch(Exception e){log.error("未找到resource下:license.xml文件!"+e);}return inputStream;}/***设置License*@return true表示已成功设置License,false表示失败*/public static boolean setWordsLicense(){if(!license.getIsLicensed()){try{license.setLicense(getLicenseInput());return license.getIsLicensed();}catch(Exception e){log.error("设置License异常!",e);}}return license.getIsLicensed();}
}

license.xml

<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>

本文标签: aspose上传,预览,下载,删除文件