mirror of
https://gitee.com/kekingcn/file-online-preview.git
synced 2026-03-18 23:23:46 +08:00
优化:重构大量代码,修复异常
This commit is contained in:
@@ -6,22 +6,20 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.common.collect.ImmutableMap;
|
||||
import com.google.common.collect.Lists;
|
||||
import cn.keking.model.ReturnResponse;
|
||||
import cn.keking.utils.FileUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.util.StreamUtils;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.*;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -33,11 +31,11 @@ public class FileController {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(FileController.class);
|
||||
|
||||
private String fileDir = ConfigConstants.getFileDir();
|
||||
@Autowired
|
||||
private FileUtils fileUtils;
|
||||
private String demoDir = "demo";
|
||||
private String demoPath = demoDir + File.separator;
|
||||
private final String fileDir = ConfigConstants.getFileDir();
|
||||
|
||||
private final String demoDir = "demo";
|
||||
|
||||
private final String demoPath = demoDir + File.separator;
|
||||
|
||||
@RequestMapping(value = "fileUpload", method = RequestMethod.POST)
|
||||
public String fileUpload(@RequestParam("file") MultipartFile file) throws JsonProcessingException {
|
||||
@@ -49,7 +47,7 @@ public class FileController {
|
||||
// Check for Windows-style path
|
||||
int winSep = fileName.lastIndexOf('\\');
|
||||
// Cut off at latest possible point
|
||||
int pos = (winSep > unixSep ? winSep : unixSep);
|
||||
int pos = (Math.max(winSep, unixSep));
|
||||
if (pos != -1) {
|
||||
fileName = fileName.substring(pos + 1);
|
||||
}
|
||||
@@ -62,13 +60,8 @@ public class FileController {
|
||||
outFile.mkdirs();
|
||||
}
|
||||
logger.info("上传文件:{}", outFile.getAbsolutePath());
|
||||
try(InputStream in = file.getInputStream();
|
||||
OutputStream ot = new FileOutputStream(fileDir + demoPath + fileName)){
|
||||
byte[] buffer = new byte[1024];
|
||||
int len;
|
||||
while ((-1 != (len = in.read(buffer)))) {
|
||||
ot.write(buffer, 0, len);
|
||||
}
|
||||
try(InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(fileDir + demoPath + fileName)) {
|
||||
StreamUtils.copy(in, out);
|
||||
return new ObjectMapper().writeValueAsString(new ReturnResponse<String>(0, "SUCCESS", null));
|
||||
} catch (IOException e) {
|
||||
logger.error("文件上传失败", e);
|
||||
@@ -94,29 +87,13 @@ public class FileController {
|
||||
List<Map<String, String>> list = Lists.newArrayList();
|
||||
File file = new File(fileDir + demoPath);
|
||||
if (file.exists()) {
|
||||
Arrays.stream(file.listFiles()).forEach(file1 -> list.add(ImmutableMap.of("fileName", demoDir + "/" + file1.getName())));
|
||||
Arrays.stream(Objects.requireNonNull(file.listFiles())).forEach(file1 -> list.add(ImmutableMap.of("fileName", demoDir + "/" + file1.getName())));
|
||||
}
|
||||
return new ObjectMapper().writeValueAsString(list);
|
||||
}
|
||||
|
||||
private String getFileName(String name) {
|
||||
String suffix = name.substring(name.lastIndexOf("."));
|
||||
String nameNoSuffix = name.substring(0, name.lastIndexOf("."));
|
||||
String uuid = UUID.randomUUID().toString();
|
||||
return uuid + "-" + nameNoSuffix + suffix;
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否存在该类型的文件
|
||||
* @return
|
||||
* @param fileName
|
||||
*/
|
||||
private boolean existsFile(String fileName) {
|
||||
boolean result = false;
|
||||
File file = new File(fileDir + demoPath + fileName);
|
||||
if (file.exists()) {
|
||||
return true;
|
||||
}
|
||||
return result;
|
||||
return file.exists();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import org.springframework.web.bind.annotation.RequestMethod;
|
||||
@Controller
|
||||
public class IndexController {
|
||||
|
||||
@RequestMapping(value = "index", method = RequestMethod.GET)
|
||||
@RequestMapping(value = "/index", method = RequestMethod.GET)
|
||||
public String go2Index(){
|
||||
return "index";
|
||||
}
|
||||
|
||||
@@ -1,17 +1,15 @@
|
||||
package cn.keking.web.controller;
|
||||
|
||||
import cn.keking.config.ConfigConstants;
|
||||
import cn.keking.hutool.URLUtil;
|
||||
import cn.keking.model.FileAttribute;
|
||||
import cn.keking.service.FilePreview;
|
||||
import cn.keking.service.FilePreviewFactory;
|
||||
|
||||
import cn.keking.service.cache.CacheService;
|
||||
import cn.keking.utils.DownloadUtils;
|
||||
import cn.keking.utils.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
@@ -22,7 +20,6 @@ import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
@@ -34,20 +31,25 @@ public class OnlinePreviewController {
|
||||
|
||||
private final Logger logger = LoggerFactory.getLogger(OnlinePreviewController.class);
|
||||
|
||||
@Autowired
|
||||
private FilePreviewFactory previewFactory;
|
||||
private final FilePreviewFactory previewFactory;
|
||||
|
||||
@Autowired
|
||||
private CacheService cacheService;
|
||||
private final CacheService cacheService;
|
||||
|
||||
private final FileUtils fileUtils;
|
||||
|
||||
private final DownloadUtils downloadUtils;
|
||||
|
||||
public OnlinePreviewController(FilePreviewFactory filePreviewFactory,
|
||||
FileUtils fileUtils,
|
||||
CacheService cacheService,
|
||||
DownloadUtils downloadUtils) {
|
||||
this.previewFactory = filePreviewFactory;
|
||||
this.fileUtils = fileUtils;
|
||||
this.cacheService = cacheService;
|
||||
this.downloadUtils = downloadUtils;
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private FileUtils fileUtils;
|
||||
|
||||
/**
|
||||
* @param url
|
||||
* @param model
|
||||
* @return
|
||||
*/
|
||||
@RequestMapping(value = "/onlinePreview", method = RequestMethod.GET)
|
||||
public String onlinePreview(String url, Model model, HttpServletRequest req) {
|
||||
FileAttribute fileAttribute = fileUtils.getFileAttribute(url);
|
||||
@@ -66,7 +68,7 @@ public class OnlinePreviewController {
|
||||
String currentUrl = req.getParameter("currentUrl");
|
||||
logger.info("预览文件url:{},urls:{}", currentUrl, urls);
|
||||
String[] imgs = urls.split("\\|");
|
||||
List imgurls = Arrays.asList(imgs);
|
||||
List<String> imgurls = Arrays.asList(imgs);
|
||||
model.addAttribute("imgurls", imgurls);
|
||||
model.addAttribute("currentUrl", currentUrl);
|
||||
return "picture";
|
||||
@@ -75,31 +77,16 @@ public class OnlinePreviewController {
|
||||
* 根据url获取文件内容
|
||||
* 当pdfjs读取存在跨域问题的文件时将通过此接口读取
|
||||
*
|
||||
* @param urlPath
|
||||
* @param resp
|
||||
* @param urlPath url
|
||||
* @param response response
|
||||
*/
|
||||
@RequestMapping(value = "/getCorsFile", method = RequestMethod.GET)
|
||||
public void getCorsFile(String urlPath, HttpServletResponse resp) {
|
||||
InputStream inputStream = null;
|
||||
public void getCorsFile(String urlPath, HttpServletResponse response) {
|
||||
logger.info("下载跨域pdf文件url:{}", urlPath);
|
||||
try {
|
||||
URL url = new URL(URLUtil.normalize(urlPath, true));
|
||||
//打开请求连接
|
||||
URLConnection connection = url.openConnection();
|
||||
HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
|
||||
httpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
|
||||
inputStream = httpURLConnection.getInputStream();
|
||||
byte[] bs = new byte[1024];
|
||||
int len;
|
||||
while (-1 != (len = inputStream.read(bs))) {
|
||||
resp.getOutputStream().write(bs, 0, len);
|
||||
}
|
||||
downloadUtils.saveToOutputStreamFormUrl(urlPath, response.getOutputStream());
|
||||
} catch (IOException e) {
|
||||
logger.error("下载跨域pdf文件异常,url:{}", urlPath, e);
|
||||
} finally {
|
||||
if (inputStream != null) {
|
||||
IOUtils.closeQuietly(inputStream);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ public class BaseUrlFilter implements Filter {
|
||||
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
public void init(FilterConfig filterConfig) {
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
package cn.keking.web.filter;
|
||||
|
||||
import cn.keking.config.ConfigConstants;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
|
||||
import javax.servlet.*;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
@@ -15,40 +12,12 @@ import java.io.IOException;
|
||||
public class ChinesePathFilter implements Filter {
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
public void init(FilterConfig filterConfig) {
|
||||
}
|
||||
|
||||
private static String BASE_URL;
|
||||
|
||||
public static String getBaseUrl() {
|
||||
String baseUrl;
|
||||
try {
|
||||
baseUrl = (String) RequestContextHolder.currentRequestAttributes().getAttribute("baseUrl",0);
|
||||
} catch (Exception e) {
|
||||
baseUrl = BASE_URL;
|
||||
}
|
||||
return baseUrl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
request.setCharacterEncoding("UTF-8");
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
String baseUrl;
|
||||
StringBuilder pathBuilder = new StringBuilder();
|
||||
pathBuilder.append(request.getScheme()).append("://").append(request.getServerName()).append(":")
|
||||
.append(request.getServerPort()).append(((HttpServletRequest) request).getContextPath()).append("/");
|
||||
String baseUrlTmp = ConfigConstants.getBaseUrl();
|
||||
if (baseUrlTmp != null && !ConfigConstants.DEFAULT_BASE_URL.equals(baseUrlTmp.toLowerCase())) {
|
||||
if (!baseUrlTmp.endsWith("/")) {
|
||||
baseUrlTmp = baseUrlTmp.concat("/");
|
||||
}
|
||||
baseUrl = baseUrlTmp;
|
||||
} else {
|
||||
baseUrl = pathBuilder.toString();
|
||||
}
|
||||
BASE_URL = baseUrl;
|
||||
request.setAttribute("baseUrl", baseUrl);
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ public class TrustHostFilter implements Filter {
|
||||
private String notTrustHost;
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
public void init(FilterConfig filterConfig) {
|
||||
ClassPathResource classPathResource = new ClassPathResource("web/notTrustHost.html");
|
||||
try {
|
||||
classPathResource.getInputStream();
|
||||
@@ -35,7 +35,7 @@ public class TrustHostFilter implements Filter {
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
|
||||
String url = getSourceUrl(request);
|
||||
String host = getHost(url);
|
||||
if (!ConfigConstants.getTrustHostSet().isEmpty() && !ConfigConstants.getTrustHostSet().contains(host)) {
|
||||
if (host != null &&!ConfigConstants.getTrustHostSet().isEmpty() && !ConfigConstants.getTrustHostSet().contains(host)) {
|
||||
String html = this.notTrustHost.replace("${current_host}", host);
|
||||
response.getWriter().write(html);
|
||||
response.getWriter().close();
|
||||
@@ -68,7 +68,7 @@ public class TrustHostFilter implements Filter {
|
||||
try {
|
||||
URL url = new URL(urlStr);
|
||||
return url.getHost().toLowerCase();
|
||||
} catch (MalformedURLException e) {
|
||||
} catch (MalformedURLException ignored) {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import java.io.IOException;
|
||||
public class WatermarkConfigFilter implements Filter {
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
public void init(FilterConfig filterConfig) {
|
||||
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user