1.优化代码结构,抽象预览接口服务

2.新增更多图片预览格式支持
This commit is contained in:
kl
2018-01-17 17:51:53 +08:00
parent 78de36964d
commit 2f86701eea
33 changed files with 447 additions and 2631 deletions

View File

@ -0,0 +1,69 @@
package cn.keking.model;
/**
* Created by kl on 2018/1/17.
* Content :
*/
public class FileAttribute {
private FileType type;
private String suffix;
private String name;
private String url;
private String decodedUrl;
public FileAttribute() {
}
public FileAttribute(FileType type, String suffix, String name, String url, String decodedUrl) {
this.type = type;
this.suffix = suffix;
this.name = name;
this.url = url;
this.decodedUrl = decodedUrl;
}
public FileType getType() {
return type;
}
public void setType(FileType type) {
this.type = type;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDecodedUrl() {
return decodedUrl;
}
public void setDecodedUrl(String decodedUrl) {
this.decodedUrl = decodedUrl;
}
}

View File

@ -0,0 +1,27 @@
package cn.keking.model;
/**
* Created by kl on 2018/1/17.
* Content :文件类型文本office压缩包等等
*/
public enum FileType {
picture("pictureFilePreviewImpl"),
compress("compressFilePreviewImpl"),
office("officeFilePreviewImpl"),
simText("simTextFilePreviewImpl"),
pdf("pdfFilePreviewImpl"),
other("otherFilePreviewImpl");
private String instanceName;
FileType(String instanceName){
this.instanceName=instanceName;
}
public String getInstanceName() {
return instanceName;
}
public void setInstanceName(String instanceName) {
this.instanceName = instanceName;
}
}

View File

@ -0,0 +1,11 @@
package cn.keking.service;
import org.springframework.ui.Model;
/**
* Created by kl on 2018/1/17.
* Content :
*/
public interface FilePreview {
String filePreviewHandle(String url, Model model);
}

View File

@ -0,0 +1,30 @@
package cn.keking.service;
import cn.keking.model.FileAttribute;
import cn.keking.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import java.util.Map;
/**
* Created by kl on 2018/1/17.
* Content :
*/
@Service
public class FilePreviewFactory {
@Autowired
FileUtils fileUtils;
@Autowired
ApplicationContext context;
public FilePreview get(String url) {
Map<String, FilePreview> filePreviewMap = context.getBeansOfType(FilePreview.class);
FileAttribute fileAttribute = fileUtils.getFileAttribute(url);
return filePreviewMap.get(fileAttribute.getType().getInstanceName());
}
}

View File

@ -0,0 +1,62 @@
package cn.keking.service.impl;
import cn.keking.model.FileAttribute;
import cn.keking.param.ReturnResponse;
import cn.keking.service.FilePreview;
import cn.keking.utils.DownloadUtils;
import cn.keking.utils.FileUtils;
import cn.keking.utils.ZipReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
/**
* Created by kl on 2018/1/17.
* Content :处理压缩包文件
*/
@Service
public class CompressFilePreviewImpl implements FilePreview{
@Autowired
FileUtils fileUtils;
@Autowired
DownloadUtils downloadUtils;
@Autowired
ZipReader zipReader;
@Override
public String filePreviewHandle(String url, Model model) {
FileAttribute fileAttribute=fileUtils.getFileAttribute(url);
String fileName=fileAttribute.getName();
String decodedUrl=fileAttribute.getDecodedUrl();
String suffix=fileAttribute.getSuffix();
String fileTree = null;
// 判断文件名是否存在(redis缓存读取)
if (!StringUtils.hasText(fileUtils.getConvertedFile(fileName))) {
ReturnResponse<String> response = downloadUtils.downLoad(decodedUrl, suffix, fileName);
if (0 != response.getCode()) {
model.addAttribute("msg", response.getMsg());
return "fileNotSupported";
}
String filePath = response.getContent();
if ("zip".equalsIgnoreCase(suffix) || "jar".equalsIgnoreCase(suffix) || "gzip".equalsIgnoreCase(suffix)) {
fileTree = zipReader.readZipFile(filePath, fileName);
} else if ("rar".equalsIgnoreCase(suffix)) {
fileTree = zipReader.unRar(filePath, fileName);
}
fileUtils.addConvertedFile(fileName, fileTree);
} else {
fileTree = fileUtils.getConvertedFile(fileName);
}
if (null != fileTree) {
model.addAttribute("fileTree", fileTree);
return "compress";
} else {
model.addAttribute("msg", "压缩文件类型不受支持尝试在压缩的时候选择RAR4格式");
return "fileNotSupported";
}
}
}

View File

@ -0,0 +1,73 @@
package cn.keking.service.impl;
import cn.keking.model.FileAttribute;
import cn.keking.param.ReturnResponse;
import cn.keking.service.FilePreview;
import cn.keking.utils.DownloadUtils;
import cn.keking.utils.FileUtils;
import cn.keking.utils.OfficeToPdf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import java.io.File;
/**
* Created by kl on 2018/1/17.
* Content :处理office文件
*/
@Service
public class OfficeFilePreviewImpl implements FilePreview {
@Autowired
FileUtils fileUtils;
@Value("${file.dir}")
String fileDir;
@Autowired
DownloadUtils downloadUtils;
@Autowired
private OfficeToPdf officeToPdf;
@Override
public String filePreviewHandle(String url, Model model) {
FileAttribute fileAttribute=fileUtils.getFileAttribute(url);
String suffix=fileAttribute.getSuffix();
String fileName=fileAttribute.getName();
String decodedUrl=fileAttribute.getDecodedUrl();
boolean isHtml = suffix.equalsIgnoreCase("xls") || suffix.equalsIgnoreCase("xlsx");
String pdfName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + (isHtml ? "html" : "pdf");
// 判断之前是否已转换过,如果转换过,直接返回,否则执行转换
if (!fileUtils.listConvertedFiles().containsKey(pdfName)) {
String filePath = fileDir + fileName;
if (!new File(filePath).exists()) {
ReturnResponse<String> response = downloadUtils.downLoad(decodedUrl, suffix, null);
if (0 != response.getCode()) {
model.addAttribute("msg", response.getMsg());
return "fileNotSupported";
}
filePath = response.getContent();
}
String outFilePath = fileDir + pdfName;
if (StringUtils.hasText(outFilePath)) {
officeToPdf.openOfficeToPDF(filePath, outFilePath);
File f = new File(filePath);
if (f.exists()) {
f.delete();
}
if (isHtml) {
// 对转换后的文件进行操作(改变编码方式)
fileUtils.doActionConvertedFile(outFilePath);
}
// 加入缓存
fileUtils.addConvertedFile(pdfName, fileUtils.getRelativePath(outFilePath));
}
}
model.addAttribute("pdfUrl", pdfName);
return isHtml ? "html" : "pdf";
}
}

View File

@ -0,0 +1,19 @@
package cn.keking.service.impl;
import cn.keking.service.FilePreview;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
/**
* Created by kl on 2018/1/17.
* Content :其他文件
*/
@Service
public class OtherFilePreviewImpl implements FilePreview {
@Override
public String filePreviewHandle(String url, Model model) {
model.addAttribute("msg", "系统还不支持该格式文件的在线预览," +
"如有需要请按下方显示的邮箱地址联系系统维护人员");
return "fileNotSupported";
}
}

View File

@ -0,0 +1,19 @@
package cn.keking.service.impl;
import cn.keking.service.FilePreview;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
/**
* Created by kl on 2018/1/17.
* Content :处理pdf文件
*/
@Service
public class PdfFilePreviewImpl implements FilePreview{
@Override
public String filePreviewHandle(String url, Model model) {
model.addAttribute("pdfUrl", url);
return "pdf";
}
}

View File

@ -0,0 +1,37 @@
package cn.keking.service.impl;
import cn.keking.service.FilePreview;
import cn.keking.utils.FileUtils;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.context.request.RequestContextHolder;
import java.util.List;
/**
* Created by kl on 2018/1/17.
* Content :图片文件处理
*/
@Service
public class PictureFilePreviewImpl implements FilePreview {
@Autowired
FileUtils fileUtils;
@Override
public String filePreviewHandle(String url, Model model) {
String fileKey=(String) RequestContextHolder.currentRequestAttributes().getAttribute("fileKey",0);
List imgUrls = Lists.newArrayList(url);
try{
imgUrls.clear();
imgUrls.addAll(fileUtils.getRedisImgUrls(fileKey));
}catch (Exception e){
imgUrls = Lists.newArrayList(url);
}
model.addAttribute("imgurls", imgUrls);
model.addAttribute("currentUrl",url);
return "picture";
}
}

View File

@ -0,0 +1,42 @@
package cn.keking.service.impl;
import cn.keking.model.FileAttribute;
import cn.keking.model.FileType;
import cn.keking.param.ReturnResponse;
import cn.keking.service.FilePreview;
import cn.keking.utils.FileUtils;
import cn.keking.utils.SimTextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import java.net.URLDecoder;
/**
* Created by kl on 2018/1/17.
* Content :处理文本文件
*/
@Service
public class SimTextFilePreviewImpl implements FilePreview{
@Autowired
SimTextUtil simTextUtil;
@Autowired
FileUtils fileUtils;
@Override
public String filePreviewHandle(String url, Model model){
FileAttribute fileAttribute=fileUtils.getFileAttribute(url);
String decodedUrl=fileAttribute.getDecodedUrl();
String fileName=fileAttribute.getName();
ReturnResponse<String> response = simTextUtil.readSimText(decodedUrl, fileName);
if (0 != response.getCode()) {
model.addAttribute("msg", response.getMsg());
return "fileNotSupported";
}
model.addAttribute("ordinaryUrl", response.getMsg());
return "txt";
}
}

View File

@ -1,13 +1,18 @@
package cn.keking.utils;
import cn.keking.model.FileAttribute;
import cn.keking.model.FileType;
import com.google.common.collect.Lists;
import org.redisson.api.RMapCache;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
@ -20,6 +25,8 @@ import java.util.Map;
*/
@Component
public class FileUtils {
Logger log= LoggerFactory.getLogger(getClass());
final String REDIS_FILE_PREVIEW_PDF_KEY = "converted-preview-pdf-file";
final String REDIS_FILE_PREVIEW_IMGS_KEY = "converted-preview-imgs-file";//压缩包内图片文件集合
@ -57,23 +64,26 @@ public class FileUtils {
* @param url
* @return
*/
public String typeFromUrl(String url) {
public FileType typeFromUrl(String url) {
String nonPramStr = url.substring(0, url.indexOf("?") != -1 ? url.indexOf("?") : url.length());
String fileName = nonPramStr.substring(nonPramStr.lastIndexOf("/") + 1);
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
if (listPictureTypes().contains(fileType.toLowerCase())) {
fileType = "picture";
return FileType.picture;
}
if (listArchiveTypes().contains(fileType.toLowerCase())) {
fileType = "compress";
return FileType.compress;
}
if (listOfficeTypes().contains(fileType.toLowerCase())) {
fileType = "office";
return FileType.office;
}
if (Arrays.asList(simText).contains(fileType.toLowerCase())) {
fileType = "simText";
return FileType.simText;
}
return fileType;
if("pdf".equalsIgnoreCase(fileType)){
return FileType.pdf;
}
return FileType.other;
}
/**
* 从url中剥离出文件名
@ -116,6 +126,8 @@ public class FileUtils {
list.add("png");
list.add("gif");
list.add("bmp");
list.add("ico");
list.add("RAW");
return list;
}
@ -235,4 +247,30 @@ public class FileUtils {
e.printStackTrace();
}
}
/**
* 获取文件后缀
* @param url
* @return
*/
private String suffixFromUrl(String url) {
String nonPramStr = url.substring(0, url.indexOf("?") != -1 ? url.indexOf("?") : url.length());
String fileName = nonPramStr.substring(nonPramStr.lastIndexOf("/") + 1);
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
return fileType;
}
public FileAttribute getFileAttribute(String url) {
String decodedUrl=null;
try {
decodedUrl = URLDecoder.decode(url, "utf-8");
}catch (UnsupportedEncodingException e){
log.debug("url解码失败");
}
// 路径转码
FileType type = typeFromUrl(url);
String suffix = suffixFromUrl(url);
// 抽取文件并返回文件列表
String fileName = getFileNameFromURL(decodedUrl);
return new FileAttribute(type,suffix,fileName,url,decodedUrl);
}
}

View File

@ -1,5 +1,6 @@
package cn.keking.utils;
import cn.keking.model.FileType;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.junrar.Archive;
@ -82,8 +83,8 @@ public class ZipReader {
}
String parentName = getLast2FileName(fullName, archiveSeparator, archiveFileName);
parentName = (level-1) + "_" + parentName;
String type=fileUtils.typeFromUrl(childName);
if (type.equalsIgnoreCase("picture")){//添加图片文件到图片列表
FileType type=fileUtils.typeFromUrl(childName);
if (type.equals(FileType.picture)){//添加图片文件到图片列表
imgUrls.add(baseUrl+childName);
}
FileNode node = new FileNode(originName, childName, parentName, new ArrayList<>(), directory,fileKey);
@ -141,8 +142,8 @@ public class ZipReader {
headersToBeExtracted.add(Collections.singletonMap(childName, header));
}
String parentName = getLast2FileName(fullName, "\\", archiveFileName);
String type=fileUtils.typeFromUrl(childName);
if (type.equalsIgnoreCase("picture")){//添加图片文件到图片列表
FileType type=fileUtils.typeFromUrl(childName);
if (type.equals(FileType.picture)){//添加图片文件到图片列表
imgUrls.add(baseUrl+childName);
}
FileNode node = new FileNode(originName, childName, parentName, new ArrayList<>(), directory,fileKey);

View File

@ -1,20 +1,16 @@
package cn.keking.web.controller;
import com.google.common.collect.Lists;
import cn.keking.param.ReturnResponse;
import cn.keking.utils.*;
import cn.keking.service.FilePreview;
import cn.keking.service.FilePreviewFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
@ -31,19 +27,9 @@ import java.util.Map;
*/
@Controller
public class OnlinePreviewController {
@Autowired
private OfficeToPdf officeToPdf;
@Autowired
FileUtils fileUtils;
@Autowired
DownloadUtils downloadUtils;
@Autowired
ZipReader zipReader;
@Autowired
SimTextUtil simTextUtil;
@Value("${file.dir}")
String fileDir;
@Autowired
FilePreviewFactory previewFactory;
/**
* @param url
@ -51,100 +37,10 @@ public class OnlinePreviewController {
* @return
*/
@RequestMapping(value = "onlinePreview", method = RequestMethod.GET)
public String onlinePreview(String url, Model model, HttpServletRequest req) throws UnsupportedEncodingException {
// 路径转码
String decodedUrl = URLDecoder.decode(url, "utf-8");
String type = fileUtils.typeFromUrl(url);
String suffix = suffixFromUrl(url);
// 抽取文件并返回文件列表
String fileName = fileUtils.getFileNameFromURL(decodedUrl);
model.addAttribute("fileType", suffix);
if (type.equalsIgnoreCase("picture")) {
List imgUrls = Lists.newArrayList(url);
try{
String fileKey = req.getParameter("fileKey");
imgUrls.clear();
imgUrls.addAll(fileUtils.getRedisImgUrls(fileKey));
}catch (Exception e){
imgUrls = Lists.newArrayList(url);
}
model.addAttribute("imgurls", imgUrls);
model.addAttribute("currentUrl",url);
return "picture";
} else if (type.equalsIgnoreCase("simText")) {
ReturnResponse<String> response = simTextUtil.readSimText(decodedUrl, fileName);
if (0 != response.getCode()) {
model.addAttribute("msg", response.getMsg());
return "fileNotSupported";
}
model.addAttribute("ordinaryUrl", response.getMsg());
return "txt";
} else if (type.equalsIgnoreCase("pdf")) {
model.addAttribute("pdfUrl", url);
return "pdf";
} else if (type.equalsIgnoreCase("compress")) {
String fileTree = null;
// 判断文件名是否存在(redis缓存读取)
if (!StringUtils.hasText(fileUtils.getConvertedFile(fileName))) {
ReturnResponse<String> response = downloadUtils.downLoad(decodedUrl, suffix, fileName);
if (0 != response.getCode()) {
model.addAttribute("msg", response.getMsg());
return "fileNotSupported";
}
String filePath = response.getContent();
if ("zip".equalsIgnoreCase(suffix) || "jar".equalsIgnoreCase(suffix) || "gzip".equalsIgnoreCase(suffix)) {
fileTree = zipReader.readZipFile(filePath, fileName);
} else if ("rar".equalsIgnoreCase(suffix)) {
fileTree = zipReader.unRar(filePath, fileName);
}
fileUtils.addConvertedFile(fileName, fileTree);
} else {
fileTree = fileUtils.getConvertedFile(fileName);
}
if (null != fileTree) {
model.addAttribute("fileTree", fileTree);
return "compress";
} else {
model.addAttribute("msg", "压缩文件类型不受支持尝试在压缩的时候选择RAR4格式");
return "fileNotSupported";
}
} else if ("office".equalsIgnoreCase(type)) {
boolean isHtml = suffix.equalsIgnoreCase("xls")
|| suffix.equalsIgnoreCase("xlsx");
String pdfName = fileName.substring(0, fileName.lastIndexOf(".") + 1) + (isHtml ? "html" : "pdf");
// 判断之前是否已转换过,如果转换过,直接返回,否则执行转换
if (!fileUtils.listConvertedFiles().containsKey(pdfName)) {
String filePath = fileDir + fileName;
if (!new File(filePath).exists()) {
ReturnResponse<String> response = downloadUtils.downLoad(decodedUrl, suffix, null);
if (0 != response.getCode()) {
model.addAttribute("msg", response.getMsg());
return "fileNotSupported";
}
filePath = response.getContent();
}
String outFilePath = fileDir + pdfName;
if (StringUtils.hasText(outFilePath)) {
officeToPdf.openOfficeToPDF(filePath, outFilePath);
File f = new File(filePath);
if (f.exists()) {
f.delete();
}
if (isHtml) {
// 对转换后的文件进行操作(改变编码方式)
fileUtils.doActionConvertedFile(outFilePath);
}
// 加入缓存
fileUtils.addConvertedFile(pdfName, fileUtils.getRelativePath(outFilePath));
}
}
model.addAttribute("pdfUrl", pdfName);
return isHtml ? "html" : "pdf";
} else {
model.addAttribute("msg", "系统还不支持该格式文件的在线预览," +
"如有需要请按下方显示的邮箱地址联系系统维护人员");
return "fileNotSupported";
}
public String onlinePreview(String url, Model model, HttpServletRequest req) {
req.setAttribute("fileKey",req.getParameter("fileKey"));
FilePreview filePreview=previewFactory.get(url);
return filePreview.filePreviewHandle(url,model);
}
/**
@ -167,13 +63,6 @@ public class OnlinePreviewController {
}
private String suffixFromUrl(String url) {
String nonPramStr = url.substring(0, url.indexOf("?") != -1 ? url.indexOf("?") : url.length());
String fileName = nonPramStr.substring(nonPramStr.lastIndexOf("/") + 1);
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
return fileType;
}
/**
* 根据url获取文件内容
* 当pdfjs读取存在跨域问题的文件时将通过此接口读取