Compare commits

..

1 Commits

Author SHA1 Message Date
dependabot[bot]
c462be239f Bump poi-scratchpad from 3.12 to 5.2.1 in /server
Bumps poi-scratchpad from 3.12 to 5.2.1.

---
updated-dependencies:
- dependency-name: org.apache.poi:poi-scratchpad
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-07-21 04:37:50 +00:00
13 changed files with 149 additions and 260 deletions

25
pom.xml
View File

@@ -10,34 +10,9 @@
<properties> <properties>
<java.version>1.8</java.version> <java.version>1.8</java.version>
<spring.boot.version>2.4.2</spring.boot.version> <spring.boot.version>2.4.2</spring.boot.version>
<poi.version>5.2.2</poi.version>
<xdocreport.version>1.0.6</xdocreport.version>
<xstream.version>1.4.19</xstream.version>
<junrar.version>7.4.1</junrar.version>
<redisson.version>3.2.0</redisson.version>
<sevenzipjbinding.version>16.02-2.01</sevenzipjbinding.version>
<tukaani.version>1.8</tukaani.version>
<jchardet.version>1.0</jchardet.version>
<antlr.version>2.7.7</antlr.version>
<concurrentlinkedhashmap.version>1.4.2</concurrentlinkedhashmap.version>
<rocksdb.version>5.17.2</rocksdb.version>
<pdfbox.version>2.0.26</pdfbox.version>
<galimatias.version>0.2.1</galimatias.version>
<bytedeco.version>1.5.2</bytedeco.version>
<opencv.version>4.1.2-1.5.2</opencv.version>
<openblas.version>0.3.6-1.5.1</openblas.version>
<ffmpeg.version>4.2.1-1.5.2</ffmpeg.version>
<itext.version>2.1.7</itext.version>
<commons-cli.version>1.2</commons-cli.version>
<commons-net.version>3.6</commons-net.version>
<commons-lang3.version>3.7</commons-lang3.version>
<commons-compress.version>1.21</commons-compress.version>
<maven.compiler.source>${java.version}</maven.compiler.source> <maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target> <maven.compiler.target>${java.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties> </properties>

View File

@@ -55,22 +55,22 @@
<dependency> <dependency>
<groupId>org.apache.poi</groupId> <groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId> <artifactId>poi</artifactId>
<version>${poi.version}</version> <version>3.17</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.poi</groupId> <groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId> <artifactId>poi-scratchpad</artifactId>
<version>${poi.version}</version> <version>5.2.1</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.poi</groupId> <groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId> <artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version> <version>3.17</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>fr.opensagres.xdocreport</groupId> <groupId>fr.opensagres.xdocreport</groupId>
<artifactId>org.apache.poi.xwpf.converter.core</artifactId> <artifactId>org.apache.poi.xwpf.converter.core</artifactId>
<version>${xdocreport.version}</version> <version>1.0.5</version>
<exclusions> <exclusions>
<exclusion> <exclusion>
<artifactId>poi</artifactId> <artifactId>poi</artifactId>
@@ -81,12 +81,12 @@
<dependency> <dependency>
<groupId>fr.opensagres.xdocreport</groupId> <groupId>fr.opensagres.xdocreport</groupId>
<artifactId>org.apache.poi.xwpf.converter.xhtml</artifactId> <artifactId>org.apache.poi.xwpf.converter.xhtml</artifactId>
<version>${xdocreport.version}</version> <version>1.0.5</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>fr.opensagres.xdocreport</groupId> <groupId>fr.opensagres.xdocreport</groupId>
<artifactId>fr.opensagres.xdocreport.document</artifactId> <artifactId>fr.opensagres.xdocreport.document</artifactId>
<version>${xdocreport.version}</version> <version>1.0.5</version>
</dependency> </dependency>
<!-- poi start --> <!-- poi start -->
@@ -94,89 +94,89 @@
<dependency> <dependency>
<groupId>net.sf.sevenzipjbinding</groupId> <groupId>net.sf.sevenzipjbinding</groupId>
<artifactId>sevenzipjbinding</artifactId> <artifactId>sevenzipjbinding</artifactId>
<version>${sevenzipjbinding.version}</version> <version>16.02-2.01</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>net.sf.sevenzipjbinding</groupId> <groupId>net.sf.sevenzipjbinding</groupId>
<artifactId>sevenzipjbinding-all-platforms</artifactId> <artifactId>sevenzipjbinding-all-platforms</artifactId>
<version>${sevenzipjbinding.version}</version> <version>16.02-2.01</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version> <version>3.7</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.redisson</groupId> <groupId>org.redisson</groupId>
<artifactId>redisson</artifactId> <artifactId>redisson</artifactId>
<version>${redisson.version}</version> <version>3.2.0</version>
</dependency> </dependency>
<!-- 解压(apache) --> <!-- 解压(apache) -->
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId> <artifactId>commons-compress</artifactId>
<version>${commons-compress.version}</version> <version>1.21</version>
</dependency> </dependency>
<!-- 解压(rar)--> <!-- 解压(rar)-->
<dependency> <dependency>
<groupId>com.github.junrar</groupId> <groupId>com.github.junrar</groupId>
<artifactId>junrar</artifactId> <artifactId>junrar</artifactId>
<version>${junrar.version}</version> <version>4.0.0</version>
</dependency> </dependency>
<!-- 解压(7z)--> <!-- 解压(7z)-->
<dependency> <dependency>
<groupId>org.tukaani</groupId> <groupId>org.tukaani</groupId>
<artifactId>xz</artifactId> <artifactId>xz</artifactId>
<version>${tukaani.version}</version> <version>1.8</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>net.sourceforge.jchardet</groupId> <groupId>net.sourceforge.jchardet</groupId>
<artifactId>jchardet</artifactId> <artifactId>jchardet</artifactId>
<version>${jchardet.version}</version> <version>1.0</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>antlr</groupId> <groupId>antlr</groupId>
<artifactId>antlr</artifactId> <artifactId>antlr</artifactId>
<version>${antlr.version}</version> <version>2.7.7</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>commons-cli</groupId> <groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId> <artifactId>commons-cli</artifactId>
<version>${commons-cli.version}</version> <version>1.2</version>
</dependency> </dependency>
<!-- FTP --> <!-- FTP -->
<dependency> <dependency>
<groupId>commons-net</groupId> <groupId>commons-net</groupId>
<artifactId>commons-net</artifactId> <artifactId>commons-net</artifactId>
<version>${commons-net.version}</version> <version>3.6</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.thoughtworks.xstream</groupId> <groupId>com.thoughtworks.xstream</groupId>
<artifactId>xstream</artifactId> <artifactId>xstream</artifactId>
<version>${xstream.version}</version> <version>1.4.18</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.googlecode.concurrentlinkedhashmap</groupId> <groupId>com.googlecode.concurrentlinkedhashmap</groupId>
<artifactId>concurrentlinkedhashmap-lru</artifactId> <artifactId>concurrentlinkedhashmap-lru</artifactId>
<version>${concurrentlinkedhashmap.version}</version> <version>1.4.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.rocksdb</groupId> <groupId>org.rocksdb</groupId>
<artifactId>rocksdbjni</artifactId> <artifactId>rocksdbjni</artifactId>
<version>${rocksdb.version}</version> <version>5.17.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.pdfbox</groupId> <groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId> <artifactId>pdfbox</artifactId>
<version>${pdfbox.version}</version> <version>2.0.24</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.pdfbox</groupId> <groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-tools</artifactId> <artifactId>pdfbox-tools</artifactId>
<version>${pdfbox.version}</version> <version>2.0.15</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.aspose</groupId> <groupId>com.aspose</groupId>
@@ -197,62 +197,62 @@
<dependency> <dependency>
<groupId>io.mola.galimatias</groupId> <groupId>io.mola.galimatias</groupId>
<artifactId>galimatias</artifactId> <artifactId>galimatias</artifactId>
<version>${galimatias.version}</version> <version>0.2.1</version>
</dependency> </dependency>
<!-- 以下是bytedeco 基于opencv ffmpeg封装的javacv用于视频处理 --> <!-- 以下是bytedeco 基于opencv ffmpeg封装的javacv用于视频处理 -->
<dependency> <dependency>
<groupId>org.bytedeco</groupId> <groupId>org.bytedeco</groupId>
<artifactId>javacv</artifactId> <artifactId>javacv</artifactId>
<version>${bytedeco.version}</version> <version>1.5.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.bytedeco</groupId> <groupId>org.bytedeco</groupId>
<artifactId>javacpp</artifactId> <artifactId>javacpp</artifactId>
<version>${bytedeco.version}</version> <version>1.5.2</version>
</dependency> </dependency>
<!-- 此版本中主要兼容linux和windows系统如需兼容其他系统平台请引入对应依赖即可 --> <!-- 此版本中主要兼容linux和windows系统如需兼容其他系统平台请引入对应依赖即可 -->
<dependency> <dependency>
<groupId>org.bytedeco</groupId> <groupId>org.bytedeco</groupId>
<artifactId>opencv</artifactId> <artifactId>opencv</artifactId>
<version>${opencv.version}</version> <version>4.1.2-1.5.2</version>
<classifier>linux-x86_64</classifier> <classifier>linux-x86_64</classifier>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.bytedeco</groupId> <groupId>org.bytedeco</groupId>
<artifactId>opencv</artifactId> <artifactId>opencv</artifactId>
<version>${opencv.version}</version> <version>4.1.2-1.5.2</version>
<classifier>windows-x86_64</classifier> <classifier>windows-x86_64</classifier>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.bytedeco</groupId> <groupId>org.bytedeco</groupId>
<artifactId>openblas</artifactId> <artifactId>openblas</artifactId>
<version>${openblas.version}</version> <version>0.3.6-1.5.1</version>
<classifier>linux-x86_64</classifier> <classifier>linux-x86_64</classifier>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.bytedeco</groupId> <groupId>org.bytedeco</groupId>
<artifactId>openblas</artifactId> <artifactId>openblas</artifactId>
<version>${openblas.version}</version> <version>0.3.6-1.5.1</version>
<classifier>windows-x86_64</classifier> <classifier>windows-x86_64</classifier>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.bytedeco</groupId> <groupId>org.bytedeco</groupId>
<artifactId>ffmpeg</artifactId> <artifactId>ffmpeg</artifactId>
<version>${ffmpeg.version}</version> <version>4.2.1-1.5.2</version>
<classifier>linux-x86_64</classifier> <classifier>linux-x86_64</classifier>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.bytedeco</groupId> <groupId>org.bytedeco</groupId>
<artifactId>ffmpeg</artifactId> <artifactId>ffmpeg</artifactId>
<version>${ffmpeg.version}</version> <version>4.2.1-1.5.2</version>
<classifier>windows-x86_64</classifier> <classifier>windows-x86_64</classifier>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.lowagie</groupId> <groupId>com.lowagie</groupId>
<artifactId>itext</artifactId> <artifactId>itext</artifactId>
<version>${itext.version}</version> <version>2.1.7</version>
</dependency> </dependency>
<dependency> <dependency>

View File

@@ -48,7 +48,8 @@ public class SimTextFilePreviewImpl implements FilePreview {
private String textData(String baseUrll) throws IOException { private String textData(String baseUrll) throws IOException {
File file = new File(baseUrll); File file = new File(baseUrll);
if(!file.exists() || file.length() == 0) { if(!file.exists() || file.length() == 0) {
return ""; String line="";
return line;
}else { }else {
String charset = EncodingDetects.getJavaEncode(baseUrll); String charset = EncodingDetects.getJavaEncode(baseUrll);
System.out.println(charset); System.out.println(charset);

View File

@@ -8,8 +8,6 @@ import cn.keking.utils.ConvertPicUtil;
import cn.keking.utils.DownloadUtils; import cn.keking.utils.DownloadUtils;
import cn.keking.utils.WebUtils; import cn.keking.utils.WebUtils;
import cn.keking.web.filter.BaseUrlFilter; import cn.keking.web.filter.BaseUrlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
@@ -20,15 +18,12 @@ import java.util.List;
/** /**
* tiff 图片文件处理 * tiff 图片文件处理
*
* @author kl (http://kailing.pub) * @author kl (http://kailing.pub)
* @since 2021/2/8 * @since 2021/2/8
*/ */
@Service @Service
public class TiffFilePreviewImpl implements FilePreview { public class TiffFilePreviewImpl implements FilePreview {
private final static Logger logger = LoggerFactory.getLogger(TiffFilePreviewImpl.class);
private final PictureFilePreviewImpl pictureFilePreview; private final PictureFilePreviewImpl pictureFilePreview;
private static final String INITIALIZE_MEMORY_SIZE = "initializeMemorySize"; private static final String INITIALIZE_MEMORY_SIZE = "initializeMemorySize";
//默认初始化 50MB 内存 //默认初始化 50MB 内存
@@ -48,25 +43,25 @@ public class TiffFilePreviewImpl implements FilePreview {
tifPreviewType = tifOnLinePreviewType; tifPreviewType = tifOnLinePreviewType;
} }
if ("tif".equalsIgnoreCase(tifPreviewType)) { if("tif".equalsIgnoreCase(tifPreviewType)){
pictureFilePreview.filePreviewHandle(url, model, fileAttribute); pictureFilePreview.filePreviewHandle(url,model,fileAttribute);
String fileSize = WebUtils.getUrlParameterReg(url, INITIALIZE_MEMORY_SIZE); String fileSize = WebUtils.getUrlParameterReg(url,INITIALIZE_MEMORY_SIZE);
if (StringUtils.hasText(fileSize)) { if(StringUtils.hasText(fileSize)){
model.addAttribute(INITIALIZE_MEMORY_SIZE, fileSize); model.addAttribute(INITIALIZE_MEMORY_SIZE,fileSize);
} else { }else {
model.addAttribute(INITIALIZE_MEMORY_SIZE, Long.toString(INITIALIZE_MEMORY_SIZE_VALUE_DEFAULT)); model.addAttribute(INITIALIZE_MEMORY_SIZE,Long.toString(INITIALIZE_MEMORY_SIZE_VALUE_DEFAULT));
} }
return TIFF_FILE_PREVIEW_PAGE; return TIFF_FILE_PREVIEW_PAGE;
} else if ("jpg".equalsIgnoreCase(tifPreviewType) || "pdf".equalsIgnoreCase(tifPreviewType)) { }else if("jpg".equalsIgnoreCase(tifPreviewType) || "pdf".equalsIgnoreCase(tifPreviewType)){
String inputFileName = url.substring(url.lastIndexOf("/") + 1); String inputFileName = url.substring(url.lastIndexOf("/") + 1);
String inputFileNamePrefix = inputFileName.substring(0, inputFileName.lastIndexOf(".")); String inputFileNamePrefix = inputFileName.substring(0, inputFileName.lastIndexOf("."));
String strLocalTif = fileDir + inputFileName; String strLocalTif = fileDir + inputFileName;
File fileTiff = new File(strLocalTif); File fileTiff = new File(strLocalTif);
// 如果本地不存在这个tif文件则下载 // 如果本地不存在这个tif文件则下载
if (!fileTiff.exists()) { if(!fileTiff.exists()){
ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, inputFileName); ReturnResponse<String> response = DownloadUtils.downLoad(fileAttribute, inputFileName);
if (response.isFailure()) { if (response.isFailure()) {
return NOT_SUPPORTED_FILE_PAGE; return NOT_SUPPORTED_FILE_PAGE;
@@ -74,23 +69,22 @@ public class TiffFilePreviewImpl implements FilePreview {
} }
String baseUrl = BaseUrlFilter.getBaseUrl(); String baseUrl = BaseUrlFilter.getBaseUrl();
if ("pdf".equalsIgnoreCase(tifPreviewType)) { if("pdf".equalsIgnoreCase(tifPreviewType)){
// 以PDF模式预览的过程 // 以PDF模式预览的过程
File filePdf = new File(fileDir + inputFileNamePrefix + ".pdf"); File filePdf = new File(fileDir + inputFileNamePrefix + ".pdf");
// 如果本地不存在对应的pdf则调用转换过程。否则直接用现有的pdf文件 // 如果本地不存在对应的pdf则调用转换过程。否则直接用现有的pdf文件
if (!filePdf.exists()) { if(!filePdf.exists()){
filePdf = ConvertPicUtil.convertTif2Pdf(strLocalTif, fileDir + inputFileNamePrefix + ".pdf"); filePdf = ConvertPicUtil.convertTif2Pdf(strLocalTif, fileDir + inputFileNamePrefix + ".pdf");
} }
// 如果pdf已经存在则将url路径加入到对象中返回给页面 // 如果pdf已经存在则将url路径加入到对象中返回给页面
assert filePdf != null; if(filePdf.exists()){
if (filePdf.exists()) {
String pdfUrl = baseUrl + inputFileNamePrefix + ".pdf"; String pdfUrl = baseUrl + inputFileNamePrefix + ".pdf";
model.addAttribute("pdfUrl", pdfUrl); model.addAttribute("pdfUrl", pdfUrl);
return PDF_FILE_PREVIEW_PAGE; return PDF_FILE_PREVIEW_PAGE;
} }
} else { }else{
// 以JPG模式预览的过程 // 以JPG模式预览的过程
String strJpgFilePathName = fileDir + inputFileNamePrefix + ".jpg"; String strJpgFilePathName = fileDir + inputFileNamePrefix + ".jpg";
// 将tif转换为jpg返回转换后的文件路径、文件名的list // 将tif转换为jpg返回转换后的文件路径、文件名的list
@@ -98,7 +92,7 @@ public class TiffFilePreviewImpl implements FilePreview {
// 将返回页面的图片url的list对象 // 将返回页面的图片url的list对象
List<String> listImageUrls = new ArrayList<>(); List<String> listImageUrls = new ArrayList<>();
// 循环拼装url的list对象 // 循环拼装url的list对象
for (String strJpg : listPic2Jpg) { for(String strJpg : listPic2Jpg){
listImageUrls.add(baseUrl + strJpg); listImageUrls.add(baseUrl + strJpg);
} }
@@ -107,8 +101,8 @@ public class TiffFilePreviewImpl implements FilePreview {
} }
// 转换后的tif没用了可以删掉了 // 转换后的tif没用了可以删掉了
if (fileTiff.exists() && !fileTiff.delete()) { if(fileTiff.exists()){
logger.error("{} 清理失败", strLocalTif); fileTiff.delete();
} }
return PICTURE_FILE_PREVIEW_PAGE; return PICTURE_FILE_PREVIEW_PAGE;

View File

@@ -27,7 +27,6 @@ public class ConvertPicUtil {
/** /**
* Tif 转 JPG。 * Tif 转 JPG。
*
* @param strInputFile 输入文件的路径和文件名 * @param strInputFile 输入文件的路径和文件名
* @param strOutputFile 输出文件的路径和文件名 * @param strOutputFile 输出文件的路径和文件名
* @return boolean 是否转换成功 * @return boolean 是否转换成功
@@ -61,8 +60,8 @@ public class ConvertPicUtil {
int intTifCount = imageDecoder.getNumPages(); int intTifCount = imageDecoder.getNumPages();
logger.info("该tif文件共有【" + intTifCount + "】页"); logger.info("该tif文件共有【" + intTifCount + "】页");
String strJpgPath; String strJpgPath = "";
String strJpgUrl; String strJpgUrl = "";
if (intTifCount == 1) { if (intTifCount == 1) {
// 如果是单页tif文件则转换的目标文件夹就在指定的位置 // 如果是单页tif文件则转换的目标文件夹就在指定的位置
strJpgPath = strOutputFile.substring(0, strOutputFile.lastIndexOf("/")); strJpgPath = strOutputFile.substring(0, strOutputFile.lastIndexOf("/"));
@@ -73,17 +72,17 @@ public class ConvertPicUtil {
// 处理目标文件夹,如果不存在则自动创建 // 处理目标文件夹,如果不存在则自动创建
File fileJpgPath = new File(strJpgPath); File fileJpgPath = new File(strJpgPath);
if (!fileJpgPath.exists() && !fileJpgPath.mkdirs()) { if (!fileJpgPath.exists()) {
logger.error("{} 创建失败", strJpgPath); fileJpgPath.mkdirs();
} }
// 循环处理每页tif文件转换为jpg // 循环处理每页tif文件转换为jpg
for (int i = 0; i < intTifCount; i++) { for (int i = 0; i < intTifCount; i++) {
String strJpg; String strJpg = "";
if (intTifCount == 1) { if(intTifCount == 1){
strJpg = strJpgPath + "/" + strFilePrefix + ".jpg"; strJpg = strJpgPath + "/" + strFilePrefix + ".jpg";
strJpgUrl = strFilePrefix + ".jpg"; strJpgUrl = strFilePrefix + ".jpg";
} else { }else{
strJpg = strJpgPath + "/" + i + ".jpg"; strJpg = strJpgPath + "/" + i + ".jpg";
strJpgUrl = strFilePrefix + "/" + i + ".jpg"; strJpgUrl = strFilePrefix + "/" + i + ".jpg";
} }
@@ -91,7 +90,7 @@ public class ConvertPicUtil {
File fileJpg = new File(strJpg); File fileJpg = new File(strJpg);
// 如果文件不存在,则生成 // 如果文件不存在,则生成
if (!fileJpg.exists()) { if(!fileJpg.exists()){
RenderedImage renderedImage = imageDecoder.decodeAsRenderedImage(i); RenderedImage renderedImage = imageDecoder.decodeAsRenderedImage(i);
ParameterBlock pb = new ParameterBlock(); ParameterBlock pb = new ParameterBlock();
pb.addSource(renderedImage); pb.addSource(renderedImage);
@@ -103,7 +102,7 @@ public class ConvertPicUtil {
renderedOp.dispose(); renderedOp.dispose();
logger.info("每页分别保存至: " + fileJpg.getCanonicalPath()); logger.info("每页分别保存至: " + fileJpg.getCanonicalPath());
} else { }else{
logger.info("JPG文件已存在 " + fileJpg.getCanonicalPath()); logger.info("JPG文件已存在 " + fileJpg.getCanonicalPath());
} }
@@ -119,19 +118,21 @@ public class ConvertPicUtil {
try { try {
fileSeekStream.close(); fileSeekStream.close();
} catch (IOException e) { } catch (IOException e) {
logger.error(e.getMessage(), e);
} }
fileSeekStream = null;
} }
} }
} }
/** /**
* 将Jpg图片转换为Pdf文件 * 将Jpg图片转换为Pdf文件
* *
* @param strJpgFile 输入的jpg的路径和文件名 * @param strJpgFile 输入的jpg的路径和文件名
* @param strPdfFile 输出的pdf的路径和文件名 * @param strPdfFile 输出的pdf的路径和文件名
* @return
*/ */
public static void convertJpg2Pdf(String strJpgFile, String strPdfFile) { public static File convertJpg2Pdf(String strJpgFile, String strPdfFile) {
Document document = new Document(); Document document = new Document();
// 设置文档页边距 // 设置文档页边距
document.setMargins(0, 0, 0, 0); document.setMargins(0, 0, 0, 0);
@@ -156,18 +157,23 @@ public class ConvertPicUtil {
document.add(image); document.add(image);
} catch (Exception ioe) { } catch (Exception ioe) {
ioe.printStackTrace(); ioe.printStackTrace();
return null;
} finally { } finally {
//关闭文档 //关闭文档
document.close(); document.close();
try { try {
assert fos != null;
fos.flush(); fos.flush();
fos.close(); fos.close();
File filePDF = new File(strPdfFile);
return filePDF;
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
return null;
} }
@@ -176,7 +182,7 @@ public class ConvertPicUtil {
* *
* @param strTifFile 输入的tif的路径和文件名 * @param strTifFile 输入的tif的路径和文件名
* @param strPdfFile 输出的pdf的路径和文件名 * @param strPdfFile 输出的pdf的路径和文件名
* @return File * @return
*/ */
public static File convertTif2Pdf(String strTifFile, String strPdfFile) { public static File convertTif2Pdf(String strTifFile, String strPdfFile) {
try { try {
@@ -192,16 +198,16 @@ public class ConvertPicUtil {
Image image; Image image;
File filePDF; File filePDF;
if (intPages == 1) { if(intPages == 1){
String strJpg = strTifFile.substring(0, strTifFile.lastIndexOf(".")) + ".jpg"; String strJpg = strTifFile.substring(0, strTifFile.lastIndexOf(".")) + ".jpg";
File fileJpg = new File(strJpg); File fileJpg = new File(strJpg);
List<String> listPic2Jpg = convertTif2Jpg(strTifFile, strJpg); List<String> listPic2Jpg = convertTif2Jpg(strTifFile, strJpg);
if (listPic2Jpg != null && fileJpg.exists()) { if(listPic2Jpg != null && fileJpg.exists()){
convertJpg2Pdf(strJpg, strPdfFile); filePDF = convertJpg2Pdf(strJpg, strPdfFile);
} }
} else { }else{
for (int i = 1; i <= intPages; i++) { for (int i = 1; i <= intPages; i++) {
image = TiffImage.getTiffImage(rafa, i); image = TiffImage.getTiffImage(rafa, i);
// 设置页面宽高与图片一致 // 设置页面宽高与图片一致
@@ -223,7 +229,7 @@ public class ConvertPicUtil {
return filePDF; return filePDF;
} catch (Exception e) { } catch (Exception e) {
logger.error(e.getMessage(), e); System.out.println(e.toString());
} }
return null; return null;
} }

View File

@@ -7,8 +7,6 @@ import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.URL; import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects; import java.util.Objects;
public class KkFileUtils { public class KkFileUtils {
@@ -17,33 +15,6 @@ public class KkFileUtils {
public static final String DEFAULT_FILE_ENCODING = "UTF-8"; public static final String DEFAULT_FILE_ENCODING = "UTF-8";
private static final List<String> illegalFileStrList = new ArrayList<>();
static {
illegalFileStrList.add("../");
illegalFileStrList.add("./");
illegalFileStrList.add("..\\");
illegalFileStrList.add(".\\");
illegalFileStrList.add("\\..");
illegalFileStrList.add("\\.");
illegalFileStrList.add("..");
illegalFileStrList.add("...");
}
/**
* 检查文件名是否合规
* @param fileName 文件名
* @return 合规结果,true:不合规false:合规
*/
public static boolean isIllegalFileName(String fileName){
for (String str: illegalFileStrList){
if(fileName.contains(str)){
return true;
}
}
return false;
}
/** /**
* 判断url是否是http资源 * 判断url是否是http资源
* *

View File

@@ -9,7 +9,6 @@ import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@@ -157,48 +156,22 @@ public class WebUtils {
String currentUrl = request.getParameter("currentUrl"); String currentUrl = request.getParameter("currentUrl");
String urlPath = request.getParameter("urlPath"); String urlPath = request.getParameter("urlPath");
if (StringUtils.isNotBlank(url)) { if (StringUtils.isNotBlank(url)) {
return decodeBase64String(url); return new String(Base64Utils.decodeFromString(url), StandardCharsets.UTF_8);
} }
if (StringUtils.isNotBlank(currentUrl)) { if (StringUtils.isNotBlank(currentUrl)) {
return decodeBase64String(currentUrl); return new String(Base64Utils.decodeFromString(currentUrl), StandardCharsets.UTF_8);
} }
if (StringUtils.isNotBlank(urlPath)) { if (StringUtils.isNotBlank(urlPath)) {
return decodeBase64String(urlPath); return new String(Base64Utils.decodeFromString(urlPath), StandardCharsets.UTF_8);
} }
if (StringUtils.isNotBlank(urls)) { if (StringUtils.isNotBlank(urls)) {
urls = decodeBase64String(urls); urls = new String(Base64Utils.decodeFromString(urls), StandardCharsets.UTF_8);
String[] images = urls.split("\\|"); String[] images = urls.split("\\|");
return images[0]; return images[0];
} }
return null; return null;
} }
/**
* 将 Base64 字符串解码,默认使用 UTF-8
* @param source 原始 Base64 字符串
* @return decoded string
*/
public static String decodeBase64String(String source) {
return decodeBase64String(source, StandardCharsets.UTF_8);
}
/**
* 将 Base64 字符串使用指定字符集解码
* @param source 原始 Base64 字符串
* @param charsets 字符集
* @return decoded string
*/
public static String decodeBase64String(String source, Charset charsets) {
/*
* url 传入的参数里加号会被替换成空格,导致解析出错,这里需要把空格替换回加号
* 有些 Base64 实现可能每 76 个字符插入换行符,也一并去掉
* https://github.com/kekingcn/kkFileView/pull/340
*/
return new String(Base64Utils.decodeFromString(
source.replaceAll(" ", "+").replaceAll("\n", "")
), charsets);
}
/** /**
* 获取 url 的 host * 获取 url 的 host
* @param urlStr url * @param urlStr url

View File

@@ -1,33 +1,26 @@
package cn.keking.web.controller; package cn.keking.web.controller;
import cn.keking.config.ConfigConstants; import cn.keking.config.ConfigConstants;
import cn.keking.model.ReturnResponse;
import cn.keking.utils.KkFileUtils;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.keking.model.ReturnResponse;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.util.StreamUtils; import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import org.springframework.web.util.HtmlUtils; import org.springframework.web.util.HtmlUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/** /**
*
* @author yudian-it * @author yudian-it
* @date 2017/12/1 * @date 2017/12/1
*/ */
@@ -40,17 +33,16 @@ public class FileController {
private final String demoDir = "demo"; private final String demoDir = "demo";
private final String demoPath = demoDir + File.separator; private final String demoPath = demoDir + File.separator;
@PostMapping("/fileUpload") @RequestMapping(value = "fileUpload", method = RequestMethod.POST)
public ReturnResponse<Object> fileUpload(@RequestParam("file") MultipartFile file) throws JsonProcessingException { public String fileUpload(@RequestParam("file") MultipartFile file) throws JsonProcessingException {
if (ConfigConstants.getFileUploadDisable()) { if (ConfigConstants.getFileUploadDisable()) {
return ReturnResponse.failure("文件传接口已禁用"); return new ObjectMapper().writeValueAsString(ReturnResponse.failure("文件传接口已禁用"));
} }
// 获取文件名 // 获取文件名
String fileName = file.getOriginalFilename(); String fileName = file.getOriginalFilename();
//判断是否为IE浏览器的文件名IE浏览器下文件名会带有盘符信息 //判断是否为IE浏览器的文件名IE浏览器下文件名会带有盘符信息
// escaping dangerous characters to prevent XSS // escaping dangerous characters to prevent XSS
assert fileName != null;
fileName = HtmlUtils.htmlEscape(fileName, StandardCharsets.UTF_8.name()); fileName = HtmlUtils.htmlEscape(fileName, StandardCharsets.UTF_8.name());
// Check for Unix-style path // Check for Unix-style path
@@ -59,47 +51,42 @@ public class FileController {
int winSep = fileName.lastIndexOf('\\'); int winSep = fileName.lastIndexOf('\\');
// Cut off at latest possible point // Cut off at latest possible point
int pos = (Math.max(winSep, unixSep)); int pos = (Math.max(winSep, unixSep));
if (pos != -1) { if (pos != -1) {
fileName = fileName.substring(pos + 1); fileName = fileName.substring(pos + 1);
} }
// 判断是否存在同名文件 // 判断是否存在同名文件
if (existsFile(fileName)) { if (existsFile(fileName)) {
return ReturnResponse.failure("存在同名文件,请先删除原有文件再次上传"); return new ObjectMapper().writeValueAsString(ReturnResponse.failure("存在同名文件,请先删除原有文件再次上传"));
} }
File outFile = new File(fileDir + demoPath); File outFile = new File(fileDir + demoPath);
if (!outFile.exists() && !outFile.mkdirs()) { if (!outFile.exists() && !outFile.mkdirs()) {
logger.error("创建文件夹【{}】失败,请检查目录权限!", fileDir + demoPath); logger.error("创建文件夹【{}】失败,请检查目录权限!",fileDir + demoPath);
} }
logger.info("上传文件:{}", fileDir + demoPath + fileName); logger.info("上传文件:{}", fileDir + demoPath + fileName);
try (InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(fileDir + demoPath + fileName)) { try(InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(fileDir + demoPath + fileName)) {
StreamUtils.copy(in, out); StreamUtils.copy(in, out);
return ReturnResponse.success(null); return new ObjectMapper().writeValueAsString(ReturnResponse.success(null));
} catch (IOException e) { } catch (IOException e) {
logger.error("文件上传失败", e); logger.error("文件上传失败", e);
return ReturnResponse.failure(); return new ObjectMapper().writeValueAsString(ReturnResponse.failure());
} }
} }
@GetMapping("/deleteFile") @RequestMapping(value = "deleteFile", method = RequestMethod.GET)
public ReturnResponse<Object> deleteFile(String fileName) throws JsonProcessingException { public String deleteFile(String fileName) throws JsonProcessingException {
if (fileName.contains("/")) { if (fileName.contains("/")) {
fileName = fileName.substring(fileName.lastIndexOf("/") + 1); fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
} }
if (KkFileUtils.isIllegalFileName(fileName)) {
return ReturnResponse.failure("非法文件名,删除失败!");
}
File file = new File(fileDir + demoPath + fileName); File file = new File(fileDir + demoPath + fileName);
logger.info("删除文件:{}", file.getAbsolutePath()); logger.info("删除文件:{}", file.getAbsolutePath());
if (file.exists() && !file.delete()) { if (file.exists() && !file.delete()) {
String msg = String.format("删除文件【%s】失败,请检查目录权限!", file.getPath()); logger.error("删除文件【{}】失败,请检查目录权限!",file.getPath());
logger.error(msg);
return ReturnResponse.failure(msg);
} }
return ReturnResponse.success(); return new ObjectMapper().writeValueAsString(ReturnResponse.success());
} }
@GetMapping("/listFiles") @RequestMapping(value = "listFiles", method = RequestMethod.GET)
public List<Map<String, String>> getFiles() throws JsonProcessingException { public String getFiles() throws JsonProcessingException {
List<Map<String, String>> list = new ArrayList<>(); List<Map<String, String>> list = new ArrayList<>();
File file = new File(fileDir + demoPath); File file = new File(fileDir + demoPath);
if (file.exists()) { if (file.exists()) {
@@ -109,7 +96,7 @@ public class FileController {
list.add(fileName); list.add(fileName);
}); });
} }
return list; return new ObjectMapper().writeValueAsString(list);
} }
private boolean existsFile(String fileName) { private boolean existsFile(String fileName) {

View File

@@ -1,7 +1,8 @@
package cn.keking.web.controller; package cn.keking.web.controller;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/** /**
* 页面跳转 * 页面跳转
@@ -11,12 +12,12 @@ import org.springframework.web.bind.annotation.GetMapping;
@Controller @Controller
public class IndexController { public class IndexController {
@GetMapping( "/index") @RequestMapping(value = "/index", method = RequestMethod.GET)
public String go2Index(){ public String go2Index(){
return "index"; return "index";
} }
@GetMapping( "/") @RequestMapping(value = "/", method = RequestMethod.GET)
public String root() { public String root() {
return "redirect:/index"; return "redirect:/index";
} }

View File

@@ -16,7 +16,8 @@ import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.Model; import org.springframework.ui.Model;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils; import org.springframework.web.util.HtmlUtils;
@@ -52,11 +53,11 @@ public class OnlinePreviewController {
this.otherFilePreview = otherFilePreview; this.otherFilePreview = otherFilePreview;
} }
@GetMapping( "/onlinePreview") @RequestMapping(value = "/onlinePreview")
public String onlinePreview(String url, Model model, HttpServletRequest req) { public String onlinePreview(String url, Model model, HttpServletRequest req) {
String fileUrl; String fileUrl;
try { try {
fileUrl = WebUtils.decodeBase64String(url); fileUrl = new String(Base64.decodeBase64(url), StandardCharsets.UTF_8);
} catch (Exception ex) { } catch (Exception ex) {
String errorMsg = String.format(BASE64_DECODE_ERROR_MSG, "url"); String errorMsg = String.format(BASE64_DECODE_ERROR_MSG, "url");
return otherFilePreview.notSupportedFile(model, errorMsg); return otherFilePreview.notSupportedFile(model, errorMsg);
@@ -68,11 +69,11 @@ public class OnlinePreviewController {
return filePreview.filePreviewHandle(fileUrl, model, fileAttribute); return filePreview.filePreviewHandle(fileUrl, model, fileAttribute);
} }
@GetMapping( "/picturesPreview") @RequestMapping(value = "/picturesPreview")
public String picturesPreview(String urls, Model model, HttpServletRequest req) throws UnsupportedEncodingException { public String picturesPreview(String urls, Model model, HttpServletRequest req) throws UnsupportedEncodingException {
String fileUrls; String fileUrls;
try { try {
fileUrls = WebUtils.decodeBase64String(urls); fileUrls = new String(Base64.decodeBase64(urls));
// 防止XSS攻击 // 防止XSS攻击
fileUrls = HtmlUtils.htmlEscape(fileUrls); fileUrls = HtmlUtils.htmlEscape(fileUrls);
} catch (Exception ex) { } catch (Exception ex) {
@@ -103,16 +104,15 @@ public class OnlinePreviewController {
* @param urlPath url * @param urlPath url
* @param response response * @param response response
*/ */
@GetMapping("/getCorsFile") @RequestMapping(value = "/getCorsFile", method = RequestMethod.GET)
public void getCorsFile(String urlPath, HttpServletResponse response) { public void getCorsFile(String urlPath, HttpServletResponse response) {
try { try {
urlPath = WebUtils.decodeBase64String(urlPath); urlPath = new String(Base64.decodeBase64(urlPath), StandardCharsets.UTF_8);
} catch (Exception ex) { } catch (Exception ex) {
logger.error(String.format(BASE64_DECODE_ERROR_MSG, urlPath),ex); logger.error(String.format(BASE64_DECODE_ERROR_MSG, urlPath, ex));
return; return;
} }
if (urlPath.toLowerCase().startsWith("file:") || urlPath.toLowerCase().startsWith("file%3") if (urlPath == null || urlPath.toLowerCase().startsWith("file:") || urlPath.toLowerCase().startsWith("file%3") || !urlPath.toLowerCase().startsWith("http")) {
|| !urlPath.toLowerCase().startsWith("http")) {
logger.info("读取跨域文件异常可能存在非法访问urlPath{}", urlPath); logger.info("读取跨域文件异常可能存在非法访问urlPath{}", urlPath);
return; return;
} }
@@ -132,7 +132,7 @@ public class OnlinePreviewController {
* *
* @param url 请编码后在入队 * @param url 请编码后在入队
*/ */
@GetMapping("/addTask") @RequestMapping("/addTask")
@ResponseBody @ResponseBody
public String addQueueTask(String url) { public String addQueueTask(String url) {
logger.info("添加转码队列url{}", url); logger.info("添加转码队列url{}", url);

View File

@@ -48,24 +48,15 @@ public class AttributeSetFilter implements Filter {
private void setWatermarkAttribute(ServletRequest request) { private void setWatermarkAttribute(ServletRequest request) {
String watermarkTxt = request.getParameter("watermarkTxt"); String watermarkTxt = request.getParameter("watermarkTxt");
request.setAttribute("watermarkTxt", watermarkTxt != null ? watermarkTxt : WatermarkConfigConstants.getWatermarkTxt()); request.setAttribute("watermarkTxt", watermarkTxt != null ? watermarkTxt : WatermarkConfigConstants.getWatermarkTxt());
String watermarkXSpace = request.getParameter("watermarkXSpace"); request.setAttribute("watermarkXSpace", WatermarkConfigConstants.getWatermarkXSpace());
request.setAttribute("watermarkXSpace", watermarkXSpace != null ? watermarkXSpace : WatermarkConfigConstants.getWatermarkXSpace()); request.setAttribute("watermarkYSpace", WatermarkConfigConstants.getWatermarkYSpace());
String watermarkYSpace = request.getParameter("watermarkYSpace"); request.setAttribute("watermarkFont", WatermarkConfigConstants.getWatermarkFont());
request.setAttribute("watermarkYSpace", watermarkYSpace != null ? watermarkYSpace : WatermarkConfigConstants.getWatermarkYSpace()); request.setAttribute("watermarkFontsize", WatermarkConfigConstants.getWatermarkFontsize());
String watermarkFont = request.getParameter("watermarkFont"); request.setAttribute("watermarkColor", WatermarkConfigConstants.getWatermarkColor());
request.setAttribute("watermarkFont", watermarkFont != null ? watermarkFont : WatermarkConfigConstants.getWatermarkFont()); request.setAttribute("watermarkAlpha", WatermarkConfigConstants.getWatermarkAlpha());
String watermarkFontsize = request.getParameter("watermarkFontsize"); request.setAttribute("watermarkWidth", WatermarkConfigConstants.getWatermarkWidth());
request.setAttribute("watermarkFontsize", watermarkFontsize != null ? watermarkFontsize : WatermarkConfigConstants.getWatermarkFontsize()); request.setAttribute("watermarkHeight", WatermarkConfigConstants.getWatermarkHeight());
String watermarkColor = request.getParameter("watermarkColor"); request.setAttribute("watermarkAngle", WatermarkConfigConstants.getWatermarkAngle());
request.setAttribute("watermarkColor", watermarkColor != null ? watermarkColor : WatermarkConfigConstants.getWatermarkColor());
String watermarkAlpha = request.getParameter("watermarkAlpha");
request.setAttribute("watermarkAlpha", watermarkAlpha != null ? watermarkAlpha : WatermarkConfigConstants.getWatermarkAlpha());
String watermarkWidth = request.getParameter("watermarkWidth");
request.setAttribute("watermarkWidth", watermarkWidth != null ? watermarkWidth : WatermarkConfigConstants.getWatermarkWidth());
String watermarkHeight = request.getParameter("watermarkHeight");
request.setAttribute("watermarkHeight", watermarkHeight != null ? watermarkHeight : WatermarkConfigConstants.getWatermarkHeight());
String watermarkAngle = request.getParameter("watermarkAngle");
request.setAttribute("watermarkAngle", watermarkAngle != null ? watermarkAngle : WatermarkConfigConstants.getWatermarkAngle());
} }
@Override @Override

View File

@@ -1,7 +1,6 @@
package cn.keking.web.filter; package cn.keking.web.filter;
import cn.keking.config.ConfigConstants; import cn.keking.config.ConfigConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.RequestContextHolder;
import javax.servlet.*; import javax.servlet.*;
@@ -19,7 +18,7 @@ public class BaseUrlFilter implements Filter {
public static String getBaseUrl() { public static String getBaseUrl() {
String baseUrl; String baseUrl;
try { try {
baseUrl = (String) RequestContextHolder.currentRequestAttributes().getAttribute("baseUrl", 0); baseUrl = (String) RequestContextHolder.currentRequestAttributes().getAttribute("baseUrl",0);
} catch (Exception e) { } catch (Exception e) {
baseUrl = BASE_URL; baseUrl = BASE_URL;
} }
@@ -34,28 +33,19 @@ public class BaseUrlFilter implements Filter {
@Override @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
String baseUrl; String baseUrl;
String configBaseUrl = ConfigConstants.getBaseUrl(); StringBuilder pathBuilder = new StringBuilder();
pathBuilder.append(request.getScheme()).append("://").append(request.getServerName()).append(":")
final HttpServletRequest servletRequest = (HttpServletRequest) request; .append(request.getServerPort()).append(((HttpServletRequest) request).getContextPath()).append("/");
//1、支持通过 http header 中 X-Base-Url 来动态设置 baseUrl 以支持多个域名/项目的共享使用 String baseUrlTmp = ConfigConstants.getBaseUrl();
final String urlInHeader = servletRequest.getHeader("X-Base-Url"); if (baseUrlTmp != null && !ConfigConstants.DEFAULT_BASE_URL.equalsIgnoreCase(baseUrlTmp)) {
if (StringUtils.isNotEmpty(urlInHeader)) { if (!baseUrlTmp.endsWith("/")) {
baseUrl = urlInHeader; baseUrlTmp = baseUrlTmp.concat("/");
} else if (configBaseUrl != null && !ConfigConstants.DEFAULT_BASE_URL.equalsIgnoreCase(configBaseUrl)) { }
//2、如果配置文件中配置了 baseUrl 且不为 default 则以配置文件为准 baseUrl = baseUrlTmp;
baseUrl = configBaseUrl;
} else { } else {
//3、默认动态拼接 baseUrl baseUrl = pathBuilder.toString();
baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ servletRequest.getContextPath() + "/";
} }
if (!baseUrl.endsWith("/")) {
baseUrl = baseUrl.concat("/");
}
BASE_URL = baseUrl; BASE_URL = baseUrl;
request.setAttribute("baseUrl", baseUrl); request.setAttribute("baseUrl", baseUrl);
filterChain.doFilter(request, response); filterChain.doFilter(request, response);

View File

@@ -2,17 +2,17 @@ package cn.keking.web.filter;
import cn.keking.config.ConfigConstants; import cn.keking.config.ConfigConstants;
import cn.keking.utils.WebUtils; import cn.keking.utils.WebUtils;
import java.io.IOException; import org.apache.commons.lang3.StringUtils;
import java.nio.charset.StandardCharsets;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.util.Base64Utils;
import org.springframework.util.FileCopyUtils; import org.springframework.util.FileCopyUtils;
import javax.servlet.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
/** /**
* @author chenjh * @author chenjh
* @since 2020/2/18 19:13 * @since 2020/2/18 19:13