Commit 45f69e61 authored by shulidong's avatar shulidong

文件上传及word转pdf(未上传business下的lib jar)

parent b6b38a9b
...@@ -28,6 +28,16 @@ ...@@ -28,6 +28,16 @@
<scope>system</scope> <scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/jna-platform-5.6.0.jar</systemPath> <systemPath>${project.basedir}/src/main/resources/jna-platform-5.6.0.jar</systemPath>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId> <artifactId>spring-boot-starter-data-jpa</artifactId>
...@@ -37,6 +47,7 @@ ...@@ -37,6 +47,7 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId> <artifactId>spring-boot-starter-json</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId> <artifactId>spring-boot-starter</artifactId>
...@@ -70,6 +81,13 @@ ...@@ -70,6 +81,13 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId> <artifactId>spring-boot-starter-websocket</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
</dependency>
<dependency> <dependency>
<groupId>com.github.chocoboxxf</groupId> <groupId>com.github.chocoboxxf</groupId>
<artifactId>opentsdb-sdk-java</artifactId> <artifactId>opentsdb-sdk-java</artifactId>
...@@ -114,6 +132,10 @@ ...@@ -114,6 +132,10 @@
<groupId>com.playtika.testcontainers</groupId> <groupId>com.playtika.testcontainers</groupId>
<artifactId>embedded-mysql</artifactId> <artifactId>embedded-mysql</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId> <artifactId>spring-boot-starter-security</artifactId>
...@@ -153,7 +175,22 @@ ...@@ -153,7 +175,22 @@
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
<version>16.0.1</version> <version>16.0.1</version>
</dependency> </dependency>
<!-- https://mvnrepository.com/artifact/net.oschina.zcx7878/fastdfs-client-java -->
<dependency>
<groupId>net.oschina.zcx7878</groupId>
<artifactId>fastdfs-client-java</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>com.github.tobato</groupId>-->
<!--<artifactId>fastdfs-client</artifactId>-->
<!--</dependency>-->
<dependency>
<groupId>com.aspose</groupId> <!--自定义-->
<artifactId>words</artifactId> <!--自定义-->
<version>1.0</version> <!--自定义-->
<scope>system</scope> <!--system,类似provided,需要显式提供依赖的jar以后,Maven就不会在Repository中查找它-->
<systemPath>${basedir}/lib/words.jar</systemPath> <!--项目根目录下的lib文件夹下-->
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
......
package cn.wise.sc.energy.power.plant.business.config;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import java.nio.charset.Charset;
/**
* @date :Created in 2019-03-21 10:21
* @description:用途:
*/
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
private ObjectMapper objectMapper = new ObjectMapper();
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class<T> clazz;
static {
//解决fastJson autoType is not support错误
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
}
public FastJsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return JSON.parseObject(str, clazz);
}
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
protected JavaType getJavaType(Class<?> clazz) {
return TypeFactory.defaultInstance().constructType(clazz);
}
}
package cn.wise.sc.energy.power.plant.business.controller;
import cn.wise.sc.energy.power.plant.business.utils.dfs.FastDFSUtils;
import cn.wise.sc.energy.power.plant.business.utils.dfs.FileTypeUtil;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 附件管理Controller
* @author ztw
*/
@RestController
@RequestMapping("/enclosure")
public class EntityEnclosureController {
private static final Logger logger = LoggerFactory.getLogger("adminLogger");
@Autowired
protected HttpServletResponse response;
@Autowired
protected HttpServletRequest request;
//@ApiOperation(value = "单个文件上传")
@PostMapping("/fileUpLoad")
public BaseResponse fileUpLoad(MultipartFile file){
Map<String,Object> map = new HashMap<>();
String filePath = null;
String fileName = null;
String extName = null;
try {
filePath = FastDFSUtils.uploadPic(file.getBytes(),file.getOriginalFilename(),file.getSize());
fileName = file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf("."));
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String picUrl = filePath;
map.put("fileUrl",picUrl);
map.put("extName",extName);
map.put("fileName",fileName);
String pdfPath = FastDFSUtils.conventAndUpload(file.getInputStream(),fileName);
map.put("pdfPath",pdfPath);
return BaseResponse.okData(map);
}catch (Exception e){
logger.error(e.toString());
}
return BaseResponse.errorMsg("失败");
}
//@ApiOperation(value = "单个图片上传")
@PostMapping("/imgUpLoad")
public BaseResponse imgUpLoad(MultipartFile file){
Map<String,Object> map = new HashMap<>();
String filePath = null;
String fileName = null;
String extName = null;
try {
if(!FileTypeUtil.isImageByExtension(file.getOriginalFilename())){
return BaseResponse.errorMsg("请上传有效图片");
}
filePath = FastDFSUtils.uploadPic(file.getBytes(),file.getOriginalFilename(),file.getSize());
fileName = file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf("."));
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String picUrl = filePath;
map.put("fileUrl",picUrl);
map.put("fileName",fileName);
map.put("extName",extName);
return BaseResponse.okData(map);
}catch (Exception e){
logger.error(e.toString());
}
return BaseResponse.errorMsg("失败");
}
//@ApiOperation(value = "多个文件上传")
@PostMapping("/filesUpLoad")
public BaseResponse filesUpLoad(HttpServletRequest request){
Map<String,Object> map = new HashMap<>();
List<MultipartFile> files = null;
String filePath = null;
String fileName = null;
String extName = null;
List<Map<String,Object>> filePathList = null;
try {
filePathList = new ArrayList<>();
files = ((MultipartHttpServletRequest)request).getFiles("files");
if(files != null && files.size() > 0) {
for (MultipartFile file : files) {
Map<String,Object> mapSub = new HashMap<>();
filePath = FastDFSUtils.uploadPic(file.getBytes(), file.getOriginalFilename(), file.getSize());
fileName = file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf("."));
extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String picUrl = filePath;
mapSub.put("fileUrl",picUrl);
mapSub.put("fileName",fileName);
mapSub.put("extName",extName);
filePathList.add(mapSub);
}
}else {
return BaseResponse.errorMsg("没有文件");
}
return BaseResponse.okData(map);
}catch (Exception e){
logger.error(e.toString());
}
return BaseResponse.errorMsg("失败");
}
//@ApiOperation(value = "单个文件下载")
@PostMapping("/fileDownload")
public BaseResponse fileDownload(String fileUrl,String fileName,String extName){
OutputStream out = null;
try {
response.setHeader("Content-Disposition", "attachment;filename="+fileName+extName);
response.setContentType("application/force-download");
out = response.getOutputStream();
fileUrl = fileUrl.substring(fileUrl.indexOf("g"));
byte[] by = FastDFSUtils.fileDownload(fileUrl);
out.write(by);
out.close();
return BaseResponse.okMsg("成功");
}catch (Exception e){
logger.error(e.toString());
}
return BaseResponse.errorMsg("失败");
}
//@ApiOperation(value = "app扫描二维码下载")
@GetMapping("/appDownload")
public BaseResponse appDownload(String fileUrl){
Map<String,Object> map = new HashMap<>();
OutputStream out = null;
try {
response.setHeader("Content-Disposition", "attachment;filename=app-release.apk");
response.setContentType("application/force-download");
out = response.getOutputStream();
fileUrl = fileUrl.substring(fileUrl.indexOf("g"));
byte[] by = FastDFSUtils.fileDownload(fileUrl);
out.write(by);
out.close();
return BaseResponse.okMsg("成功");
}catch (Exception e){
logger.error(e.toString());
}
return BaseResponse.errorMsg("失败");
}
//@ApiOperation(value = "删除相关文件")
@PostMapping("/fileDeleted")
public BaseResponse fileDeleted(String[] filePaths){
Map<String,Object> map = new HashMap<>();
String filePath = null;
boolean rel = false;
try {
for(String url : filePaths){
/*filePath = url.substring(0,url.indexOf("g"));*/
rel = FastDFSUtils.deletePic(url);
if(!rel){
return BaseResponse.errorMsg("删除失败");
}
}
return BaseResponse.okMsg("成功");
}catch (Exception e){
logger.error(e.toString());
}
return BaseResponse.errorMsg("失败");
}
}
package cn.wise.sc.energy.power.plant.business.domain;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* @author neo.shu
* @since 2020/9/10 18:29
*/
@Entity
@Data
@NoArgsConstructor
@Table(name = "caseAnalysisInfo")
public class CaseAnalysisInfo extends AbstractEntity<String>{
@Id
@Column(name = "caseid")
private String caseId;
@Override
public String getId() {
return getCaseId();
}
}
package cn.wise.sc.energy.power.plant.business.exception;
/**
* 封装fastdfs的异常,使用运行时异常
*
* @author yuqih
* @author tobato
*
*/
public abstract class FdfsException extends RuntimeException {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
protected FdfsException(String message) {
super(message);
}
/**
* @param message
* @param cause
*/
protected FdfsException(String message, Throwable cause) {
super(message, cause);
}
}
\ No newline at end of file
package cn.wise.sc.energy.power.plant.business.exception;
/**
* 从Url解析StorePath文件路径对象错误
*
* @author wuyf
*
*/
public class FdfsUnsupportStorePathException extends FdfsException {
/**
* serialVersionUID
*/
private static final long serialVersionUID = 8116336411011152869L;
public FdfsUnsupportStorePathException(String message) {
super(message);
}
}
\ No newline at end of file
package cn.wise.sc.energy.power.plant.business.utils;
import cn.hutool.core.io.file.FileReader;
import cn.wise.sc.energy.power.plant.business.utils.dfs.FastDFSUtils;
import com.aspose.words.Document;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
/**
* @author neo.shu
* @since 2020/9/10 20:38
*/
public class Word2PdfUtil {
public static void main(String[] args) {
try {
long time = System.currentTimeMillis();
File file = new File("C:\\Users\\admin\\Desktop\\发电机远程智能监测与诊断系统设计方案(舒立冬).docx");
Document document = new Document(new FileInputStream(file));
//pdf路径
File outputFile = new File("temp-" + System.currentTimeMillis() + ".pdf");
//操作文档保存
document.save(outputFile.getAbsolutePath(), com.aspose.words.SaveFormat.PDF);
FileReader fileReader = new FileReader(outputFile.getAbsolutePath());
String filePath = FastDFSUtils.uploadPic(fileReader.readBytes(), outputFile.getName(), file.length());
long time1 = System.currentTimeMillis();
System.out.println((time1 - time) / 1000);
System.out.println(filePath);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
package cn.wise.sc.energy.power.plant.business.utils.dfs;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileReader;
import com.aspose.words.Document;
import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.csource.fastdfs.UploadCallback;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 上传图片到FastDFS
*/
public class FastDFSUtils {
static {
try {
ClientGlobal.initByProperties(FastDFSUtils.class.getClassLoader().getResource("fastdfs-client.properties").getPath());
// ClientGlobal.initByProperties("fastdfs-client.properties");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
}
}
public static String[] uploadPic(String path, String fileName, long size) {
String[] fileIds = null;
try {
// ClientGloble 读配置文件
// 老大客户端
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
String extName = FilenameUtils.getExtension(fileName);
NameValuePair[] meta_list = new NameValuePair[3];
meta_list[0] = new NameValuePair("fileName", fileName);
meta_list[1] = new NameValuePair("fileExt", extName);
meta_list[2] = new NameValuePair("fileSize", String.valueOf(size));
// http://172.16.15.244:8081/group1/M00/00/00/rBAP9FfFG62AZsuBAADeW7MfEHA287.png
// group1/M00/00/01/wKjIgFWOYc6APpjAAAD-qk29i78248.jpg
fileIds = storageClient.upload_file(path, extName, meta_list);
} catch (Exception e) {
e.printStackTrace();
}
return fileIds;
}
public static String[] uploadPic(InputStream inStream, String fileName, long size) {
String[] fileIds = null;
try {
// ClientGloble 读配置文件
// 老大客户端
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
String extName = FilenameUtils.getExtension(fileName);
NameValuePair[] meta_list = new NameValuePair[3];
meta_list[0] = new NameValuePair("fileName", fileName);
meta_list[1] = new NameValuePair("fileExt", extName);
meta_list[2] = new NameValuePair("fileSize", String.valueOf(size));
// http://172.16.15.244:8081/group1/M00/00/00/rBAP9FfFG62AZsuBAADeW7MfEHA287.png
// group1/M00/00/01/wKjIgFWOYc6APpjAAAD-qk29i78248.jpg
fileIds = storageClient.upload_file(null, size, new UploadFileSender(inStream), extName, meta_list);
} catch (Exception e) {
e.printStackTrace();
}
return fileIds;
}
public static byte[] fileDownload(String fileUrl) {
byte[] by = null;
TrackerClient trackerClient = null;
TrackerServer trackerServer = null;
StorageClient1 storageClient1 = null;
StorageServer storageServer = null;
try {
trackerClient = new TrackerClient();
trackerServer = trackerClient.getConnection();
storageClient1 = new StorageClient1(trackerServer, storageServer);
// 根据文件标识下载文件
by = storageClient1.download_file1(fileUrl);
// 将数据写入输出流
} catch (IOException e) {
e.printStackTrace();
} catch (MyException e) {
e.printStackTrace();
}
return by;
}
public static String uploadPic(byte[] pic, String fileName, long size) {
String[] fileIds = null;
try {
// ClientGloble 读配置文件
// 老大客户端
TrackerClient trackerClient = new TrackerClient();
TrackerServer trackerServer = trackerClient.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
String extName = FilenameUtils.getExtension(fileName);
// 设置图片meta信息
NameValuePair[] meta_list = new NameValuePair[3];
meta_list[0] = new NameValuePair("fileName", fileName);
meta_list[1] = new NameValuePair("fileExt", extName);
meta_list[2] = new NameValuePair("fileSize", String.valueOf(size));
// 上传且返回path
fileIds = storageClient.upload_file(pic, extName, meta_list);
return fileIds[0] + "/" + fileIds[1];
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* word转pdf并上传返回路径
*
* @param inputStream
* @param filename
* @return
*/
public static String conventAndUpload(InputStream inputStream, String filename) {
File outputFile = new File(filename + ".pdf");
String filePath = "";
try {
Document document = new Document(inputStream);
//pdf路径
//操作文档保存
document.save(outputFile.getAbsolutePath(), com.aspose.words.SaveFormat.PDF);
FileReader fileReader = new FileReader(outputFile.getAbsolutePath());
filePath = uploadPic(fileReader.readBytes(), outputFile.getName(), outputFile.length());
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
//删除创建的输出文件
FileUtil.del(outputFile);
return filePath;
}
}
public static boolean deletePic(String fileUrl) {
try {
TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
StorePath storePath = StorePath.praseFromUrl(fileUrl);
int i = storageClient.delete_file(storePath.getGroup(), storePath.getPath());
System.out.println(i == 0 ? "删除成功" : "删除失败:" + i);
return i == 0;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static String deletePic(String[] fileIds) {
try {
TrackerClient tracker = new TrackerClient();
TrackerServer trackerServer = tracker.getConnection();
StorageServer storageServer = null;
StorageClient storageClient = new StorageClient(trackerServer, storageServer);
int i = storageClient.delete_file(fileIds[0], fileIds[1]);
System.out.println(i == 0 ? "删除成功" : "删除失败:" + i);
} catch (Exception e) {
e.printStackTrace();
}
return fileIds[1];
}
private static class UploadFileSender implements UploadCallback {
private InputStream inStream;
public UploadFileSender(InputStream inStream) {
this.inStream = inStream;
}
@Override
public int send(OutputStream out) throws IOException {
int readBytes;
while ((readBytes = inStream.read()) > 0) {
out.write(readBytes);
}
return 0;
}
}
}
\ No newline at end of file
package cn.wise.sc.energy.power.plant.business.utils.dfs;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class FileTypeUtil {
private final static Map<String, String> FILE_TYPE_MAP = new HashMap<String, String>();
private final static List<String> imageAllowFiles = Arrays
.asList(new String[] { "png", "jpg", "jpeg", "gif", "bmp" });/* 允许上传的图片格式 */
static {
getAllFileType(); // 初始化文件类型信息
}
/**
* <p>
* Discription:[getAllFileType,常见文件头信息] 注:TXT文件没有文件头
* </p>
*/
private static void getAllFileType() {
FILE_TYPE_MAP.put("jpg", "FFD8FF"); // JPEG (jpg)
FILE_TYPE_MAP.put("png", "89504E47"); // PNG (png)
FILE_TYPE_MAP.put("gif", "47494638"); // GIF (gif)
FILE_TYPE_MAP.put("tif", "49492A00"); // TIFF (tif)
FILE_TYPE_MAP.put("bmp", "424D"); // Windows Bitmap (bmp)
FILE_TYPE_MAP.put("dwg", "41433130"); // CAD (dwg)
FILE_TYPE_MAP.put("html", "68746D6C3E"); // HTML (html)
FILE_TYPE_MAP.put("rtf", "7B5C727466"); // Rich Text Format (rtf)
FILE_TYPE_MAP.put("xml", "3C3F786D6C");
FILE_TYPE_MAP.put("zip", "504B0304");
FILE_TYPE_MAP.put("rar", "52617221");
FILE_TYPE_MAP.put("psd", "38425053"); // Photoshop (psd)
FILE_TYPE_MAP.put("eml", "44656C69766572792D646174653A"); // Email
// [thorough
// only]
// (eml)
FILE_TYPE_MAP.put("dbx", "CFAD12FEC5FD746F"); // Outlook Express (dbx)
FILE_TYPE_MAP.put("pst", "2142444E"); // Outlook (pst)
FILE_TYPE_MAP.put("xls", "D0CF11E0"); // MS Word
FILE_TYPE_MAP.put("doc", "D0CF11E0"); // MS Excel 注意:word 和 excel的文件头一样
FILE_TYPE_MAP.put("mdb", "5374616E64617264204A"); // MS Access (mdb)
FILE_TYPE_MAP.put("wpd", "FF575043"); // WordPerfect (wpd)
FILE_TYPE_MAP.put("eps", "252150532D41646F6265");
FILE_TYPE_MAP.put("ps", "252150532D41646F6265");
FILE_TYPE_MAP.put("pdf", "255044462D312E"); // Adobe Acrobat (pdf)
FILE_TYPE_MAP.put("qdf", "AC9EBD8F"); // Quicken (qdf)
FILE_TYPE_MAP.put("pwl", "E3828596"); // Windows Password (pwl)
FILE_TYPE_MAP.put("wav", "57415645"); // Wave (wav)
FILE_TYPE_MAP.put("avi", "41564920");
FILE_TYPE_MAP.put("ram", "2E7261FD"); // Real Audio (ram)
FILE_TYPE_MAP.put("rm", "2E524D46"); // Real Media (rm)
FILE_TYPE_MAP.put("mpg", "000001BA"); //
FILE_TYPE_MAP.put("mov", "6D6F6F76"); // Quicktime (mov)
FILE_TYPE_MAP.put("asf", "3026B2758E66CF11"); // Windows Media (asf)
FILE_TYPE_MAP.put("mid", "4D546864"); // MIDI (mid)
}
/**
* <p>
* Discription:[getFileTypeByStream]
* </p>
*/
public final static String getFileTypeByStream(byte[] b) {
String filetypeHex = String.valueOf(getFileHexString(b));
Iterator<Entry<String, String>> entryiterator = FILE_TYPE_MAP.entrySet().iterator();
while (entryiterator.hasNext()) {
Entry<String, String> entry = entryiterator.next();
String fileTypeHexValue = entry.getValue();
if (filetypeHex.toUpperCase().startsWith(fileTypeHexValue)) {
return entry.getKey();
}
}
return null;
}
/**
* <p>
* Discription:[getFileByFile,获取文件类型,包括图片,若格式不是已配置的,则返回null]
* </p>
*/
public final static String getFileTypeByFile(File file) {
String fileType = null;
byte[] b = new byte[50];
try {
InputStream is = new FileInputStream(file);
is.read(b);
fileType = getFileTypeByStream(b);
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fileType;
}
/**
* <p>
* Discription:[getFileHexString]
* </p>
*/
public final static String getFileHexString(byte[] b) {
StringBuilder stringBuilder = new StringBuilder();
if (b == null || b.length <= 0) {
return null;
}
for (int i = 0; i < b.length; i++) {
int v = b[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* <p>
* Discription:[getImageFileType,获取图片文件实际类型,若不是图片则返回null]
* </p>
*/
public final static String getImageFileType(File f) {
if (isImage(f)) {
try {
ImageInputStream iis = ImageIO.createImageInputStream(f);
Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
if (!iter.hasNext()) {
return null;
}
ImageReader reader = iter.next();
iis.close();
return reader.getFormatName();
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return null;
}
/**
* 只根据后缀名判断是否为图片
*
* @param file
* @return
*/
public static final boolean isImage(File file) {
return isImage(file, true);
}
/**
* <p>
* Discription:[isImage,判断文件是否为图片]
* </p>
*
* @param file
* 源文件
* @param onlyByExtension
* 是否值验证后缀名
* @return true 是 | false 否
*/
public static final boolean isImage(File file, boolean onlyByExtension) {
boolean flag = false;
try {
boolean allowFile = isImageByExtension(file.getName());
if (onlyByExtension) {
flag = allowFile;
} else {
if (allowFile) {
BufferedImage bufreader = ImageIO.read(file);
int width = bufreader.getWidth();
int height = bufreader.getHeight();
if (width == 0 || height == 0) {
flag = false;
} else {
flag = true;
}
}
}
} catch (IOException e) {
flag = false;
e.printStackTrace();
} catch (Exception e) {
flag = false;
e.printStackTrace();
}
return flag;
}
/**
* 只通过后缀名判断是否为图片
*
* @param fileName
* @return
*/
public static final boolean isImageByExtension(String fileName) {
boolean flag = false;
String fileExtName = FilenameUtils.getExtension(fileName);
if (StringUtils.isNotBlank(fileExtName)) {
flag = imageAllowFiles.contains(fileExtName.toLowerCase());
}
return flag;
}
}
package cn.wise.sc.energy.power.plant.business.utils.dfs;
import cn.wise.sc.energy.power.plant.business.exception.FdfsUnsupportStorePathException;
import org.apache.commons.lang3.Validate;
/**
* 存储文件的路径信息
*
* @author yuqih
*
*/
public class StorePath {
private String group;
private String path;
/** 解析路径 */
private static final String SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR = "/";
/** group */
private static final String SPLIT_GROUP_NAME = "group";
/**
* 存储文件路径
*/
public StorePath() {
}
/**
* 存储文件路径
*
* @param group
* @param path
*/
public StorePath(String group, String path) {
super();
this.group = group;
this.path = path;
}
/**
* @return the group
*/
public String getGroup() {
return group;
}
/**
* @param group
* the group to set
*/
public void setGroup(String group) {
this.group = group;
}
/**
* @return the path
*/
public String getPath() {
return path;
}
/**
* @param path
* the path to set
*/
public void setPath(String path) {
this.path = path;
}
/**
* 获取文件全路径
*
* @return
*/
public String getFullPath() {
return this.group.concat(SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR).concat(this.path);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "StorePath [group=" + group + ", path=" + path + "]";
}
/**
* 从Url当中解析存储路径对象
*
* @param filePath
* 有效的路径样式为(group/path) 或者 (http://ip/group/path),路径地址必须包含group
* @return
*/
public static StorePath praseFromUrl(String filePath) {
Validate.notNull(filePath, "解析文件路径不能为空");
// 获取group起始位置
int groupStartPos = getGroupStartPos(filePath);
String groupAndPath = filePath.substring(groupStartPos);
int pos = groupAndPath.indexOf(SPLIT_GROUP_NAME_AND_FILENAME_SEPERATOR);
if ((pos <= 0) || (pos == groupAndPath.length() - 1)) {
throw new FdfsUnsupportStorePathException("解析文件路径错误,有效的路径样式为(group/path) 而当前解析路径为".concat(filePath));
}
String group = groupAndPath.substring(0, pos);
String path = groupAndPath.substring(pos + 1);
return new StorePath(group, path);
}
/**
* 获得group起始位置
*
* @param filePath
*/
private static int getGroupStartPos(String filePath) {
int pos = filePath.indexOf(SPLIT_GROUP_NAME);
if ((pos == -1)) {
throw new FdfsUnsupportStorePathException("解析文件路径错误,被解析路径url没有group,当前解析路径为".concat(filePath));
}
return pos;
}
}
\ No newline at end of file
...@@ -53,7 +53,7 @@ spring: ...@@ -53,7 +53,7 @@ spring:
nodeParent: /hbase-unsecure nodeParent: /hbase-unsecure
redisson: redisson:
master-name: mymaster master-name: mymaster
address: redis://127.0.0.1:6378 address: redis://59.110.68.164:6379
password: Risen12348765 password: Risen12348765
subscriptionConnectionMinimumIdleSize: 1 subscriptionConnectionMinimumIdleSize: 1
dnsMonitoring: false dnsMonitoring: false
...@@ -77,8 +77,28 @@ spring: ...@@ -77,8 +77,28 @@ spring:
multipart: multipart:
max-request-size: 200MB max-request-size: 200MB
max-file-size: 200MB max-file-size: 200MB
#fdfs:
# so-timeout: 1501
# connect-timeout: 601
# thumb-image: #缩略图生成参数
# width: 150
# height: 150
# tracker-list: #TrackerList参数,支持多个
# - 59.110.68.164:22122
# pool:
# #从池中借出的对象的最大数目(配置为-1表示不限制)
# max-total: -1
# #获取连接时的最大等待毫秒数(默认配置为5秒)
# max-wait-millis: 5000
# #每个key最大连接数
# max-total-per-key: 50
# #每个key对应的连接池最大空闲连接数
# max-idle-per-key: 10
# #每个key对应的连接池最小空闲连接数
# max_idle_per_key: 5
opentsdb: opentsdb:
baseUrl: http://39.105.86.33:8182 baseUrl: http://39.105.86.33:8182
server: server:
port: 2020 port: 2020
\ No newline at end of file
fastdfs.connect_timeout=2000
fastdfs.network_timeout=1501
fastdfs.charset=UTF-8
fastdfs.http.tracker_http_port=8888
fastdfs.http.anti_steal_token=no
fastdfs.http.secret_key=FastDFS1234567890
fastdfs.tracker_servers=59.110.68.164:22122
#fastdfs.tracker_servers=localhost:22122
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment