java 文件上传下载及pdf预览实现(可直接copy使用)
通过java实现文件上传及下载预览可以通过路径直接访问pdf即可
·
1.所需要的包(pom.xml依赖)
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.9</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- 引入该 spring-cloud-context.jar 使 bootstrap.properties 配置文件即可生效 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-context</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/tk.mybatis/mapper-spring-boot-starter -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>18.8</version>
</dependency>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-cells</artifactId>
<version>8.5.2</version>
</dependency>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose.slides</artifactId>
<version>15.9.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<!--引入生成二维码的依赖-->
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
2.控制层(Controller)
@Value("${upload.imgs.url}")
private String uploadImgUrl;
@Autowired
FileRecordService fileRecordService;
@PostMapping("/upload")
@ApiOperation("批量上传返利入账附件")
public ResponseMsg uploadContract(@RequestParam("files") MultipartFile[] files,@Valid FileOtherKeyParam fileOtherKeyParam) {
ResponseMsg msg = new ResponseMsg();
try {msg.setData(fileRecordService.fileUpload(files,uploadImgUrl,fileOtherKeyParam));
} catch (Exception e) {
msg.setError(e.getMessage());
e.printStackTrace();
}
return msg;
}
@GetMapping("/downLoad")
@ApiOperation("文件下载")
public void downLoadContract(HttpServletRequest request, HttpServletResponse response,String filePath) {
try {
fileRecordService.fileDownloadFile(request,response,filePath,uploadImgUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
2.逻辑实现层
package com.clouderp.fileservice.service.impl;
import com.clouderp.fileservice.dto.FileOtherKeyDto;
import com.clouderp.fileservice.mapper.FileRecordMapper;
import com.clouderp.fileservice.param.FileOtherKeyParam;
import com.clouderp.fileservice.service.FileRecordService;
import com.clouderp.fileservice.utils.MD5Utils;
import com.clouderp.fileservice.utils.UploadUtil;
import com.clouderp.fileservice.utils.pdf.FileUtil;
import com.google.common.collect.Lists;
import entity.SysStaff;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;
import utils.WebUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
/**
* @Author Maynard.ran
* @Date 2022/9/7
*/
@Service
@RequiredArgsConstructor
public class FileRecordServiceImpl implements FileRecordService {
private final FileRecordMapper fileRecordMapper;
@Override
@Transactional(rollbackFor = Exception.class)
public Object fileUpload(MultipartFile[] files, String uploadImgUrl,FileOtherKeyParam fileOtherKeyParam) throws Exception{
List<Map<String, Object>> listMap= Lists.newArrayList();
//先存文件
//获取登录人员信息
SysStaff user = WebUtil.currentUser();
if(null == user || null == user.getId()){
throw new RuntimeException("请先登录后上传文件");
}
for (MultipartFile file:files) {
InputStream inputStream = file.getInputStream();
StringBuilder pdfStr = new StringBuilder();
String pdfUrl = pdfStr.append(fileOtherKeyParam.getSource()).append("/").append(fileOtherKeyParam.getModular()).append("/").append("pdf/").toString();
String fileSaveUrl = uploadImgUrl + pdfUrl;
UploadUtil.createDir(fileSaveUrl);
String md5 = MD5Utils.getMd5(file);
String ext = UploadUtil.getExt(file.getOriginalFilename());
UploadUtil.createDir(fileSaveUrl);
//pdf存一份用于预览
FileUtil.extFile(ext,file,md5+".pdf",fileSaveUrl);
//源文件也保存一份 如果源文件就是pdf则只新增一个
String originalFilePath = ext.equals("pdf") ? fileSaveUrl+md5+".pdf" : saveOriginalFile(file, uploadImgUrl,fileOtherKeyParam,inputStream,md5);
Map<String, Object> map = new HashMap<>();
map.put("name",file.getOriginalFilename());
map.put("url",pdfUrl+md5+".pdf");
map.put("originalFile",originalFilePath);
listMap.add(map);
//数据库存储一份
FileOtherKeyDto insert = FileOtherKeyDto.builder().fileName(file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf(".")))
.createId(user.getId())
.createTime(new Date())
.modular(fileOtherKeyParam.getModular())
.source(fileOtherKeyParam.getSource())
.orgFileUrl(originalFilePath)
.pdfFileUrl(pdfUrl + md5 + ".pdf")
.type(ext).build();
fileRecordMapper.insert(insert);
}
return listMap;
}
@Override
public void fileDownloadFile(HttpServletRequest request, HttpServletResponse response, String path,String uploadImagUrl) throws Exception{
Example example = new Example(FileOtherKeyDto.class);
if(path.isEmpty()){
throw new RuntimeException("文件不能为空");
}
String substring = path.substring(path.lastIndexOf(".") + 1);
example.createCriteria().andEqualTo("pdf".equals(substring) ? "pdfFileUrl" : "orgFileUrl",path);
List<FileOtherKeyDto> fileOtherKeyDtos = fileRecordMapper.selectByExample(example);
String fileName = fileOtherKeyDtos.isEmpty() || StringUtils.isEmpty(fileOtherKeyDtos.get(0).getFileName()) ?
path.substring(path.lastIndexOf("/")+1) : fileOtherKeyDtos.get(0).getFileName()+"."+substring ;
FileUtil.downloadFile(request,response,fileName,uploadImagUrl+path);
}
/**
* 上传文件
* @param file
* @param uploadImgUrl
* @param fileOtherKeyParam
* @param in
* @return
* @throws Exception
*/
private String saveOriginalFile(MultipartFile file,String uploadImgUrl,FileOtherKeyParam fileOtherKeyParam,InputStream in,String md5File) throws Exception{
String md5 = MD5Utils.md5(md5File+md5File);
String ext = UploadUtil.getExt(file.getOriginalFilename());
StringBuilder str = new StringBuilder();
str.append(fileOtherKeyParam.getSource()).append("/").append(fileOtherKeyParam.getModular()).append("/").append(ext).append("/");
UploadUtil.createDir(str.toString());
str.append(md5).append(".").append(ext);
String saveUrl = uploadImgUrl+str;
uploadFile(file,saveUrl,in);
Example example = new Example(FileOtherKeyDto.class);
example.createCriteria().andEqualTo("type",ext).andEqualTo("orgFileUrl",str.toString());
List<FileOtherKeyDto> fileOtherKeyDtos = fileRecordMapper.selectByExample(example);
return null == fileOtherKeyDtos || fileOtherKeyDtos.isEmpty() ? str.toString() : fileOtherKeyDtos.get(0).getOrgFileUrl();
}
/**
* 上传文件
* @param mFile
* @param path
* @param in
*/
public static void uploadFile(MultipartFile mFile, String path,InputStream in) {
try {
byte[] buffer = new byte[1024];
int len = 0;
File file = new File(path);
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();
}
OutputStream out = new FileOutputStream(path);
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.使用到的工具包LicenseUtil
package com.clouderp.fileservice.utils.pdf;
import com.aspose.words.FontSettings;
import com.aspose.words.License;
import org.apache.commons.lang.SystemUtils;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
/**
* aspose 破解码
*/
public class LicenseUtil {
/**
* word破解
* @return
*/
public static boolean getLicenseWord() {
if( SystemUtils.IS_OS_LINUX){
FontSettings.getDefaultInstance().setFontsFolder(File.separator + "usr"
+ File.separator + "share" + File.separator + "fonts", true);
}
boolean result = false;
try {
// 凭证
String license =
"<License>\n" +
" <Data>\n" +
" <Products>\n" +
" <Product>Aspose.Total for Java</Product>\n" +
" <Product>Aspose.Words for Java</Product>\n" +
" </Products>\n" +
" <EditionType>Enterprise</EditionType>\n" +
" <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
" <LicenseExpiry>20991231</LicenseExpiry>\n" +
" <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
" </Data>\n" +
" <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
"</License>";
InputStream is = new ByteArrayInputStream(license.getBytes("UTF-8"));
License asposeLic = new License();
asposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* execl 破解
* @return
*/
public static boolean getLicenseExecl() {
boolean result = false;
if( SystemUtils.IS_OS_LINUX){
FontSettings.getDefaultInstance().setFontsFolder(File.separator + "usr"
+ File.separator + "share" + File.separator + "fonts", true);
}
try {
// 凭证
String license =
"<License>\n" +
" <Data>\n" +
" <Products>\n" +
" <Product>Aspose.Total for Java</Product>\n" +
" <Product>Aspose.Words for Java</Product>\n" +
" </Products>\n" +
" <EditionType>Enterprise</EditionType>\n" +
" <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
" <LicenseExpiry>20991231</LicenseExpiry>\n" +
" <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
" </Data>\n" +
" <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
"</License>";
InputStream is = new ByteArrayInputStream(license.getBytes("UTF-8"));
com.aspose.cells.License asposeLic = new com.aspose.cells.License();
asposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* ppt破解
* @return
*/
public static boolean getLicensePPT() {
boolean result = false;
if( SystemUtils.IS_OS_LINUX){
FontSettings.getDefaultInstance().setFontsFolder(File.separator + "usr"
+ File.separator + "share" + File.separator + "fonts", true);
}
try {
String license =
"<License>\n" +
" <Data>\n" +
" <Products>\n" +
" <Product>Aspose.Total for Java</Product>\n" +
" <Product>Aspose.Words for Java</Product>\n" +
" </Products>\n" +
" <EditionType>Enterprise</EditionType>\n" +
" <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
" <LicenseExpiry>20991231</LicenseExpiry>\n" +
" <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
" </Data>\n" +
" <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
"</License>";
InputStream is = new ByteArrayInputStream(license.getBytes("UTF-8"));
com.aspose.slides.License aposeLic = new com.aspose.slides.License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
3.1 使用到的工具包FileUtil
package com.clouderp.fileservice.utils.pdf;
import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.aspose.words.SaveFormat;
import com.clouderp.fileservice.param.FileOtherKeyParam;
import com.clouderp.fileservice.utils.UploadUtil;
import com.clouderp.fileservice.utils.MD5Utils;
import com.google.common.collect.Lists;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import freemarker.template.Configuration;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import utils.ExportUtil;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 文件转换为pdf
*/
public class FileUtil {
public static void downloadFile(HttpServletRequest request, HttpServletResponse response, String fileName, String filePath) throws UnsupportedEncodingException {
File file = new File(filePath);
response.reset();
response.setCharacterEncoding("utf-8");
response.setContentLength((int) file.length());
//文件后缀
String fileNameURL = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-disposition", "attachment;filename="+fileNameURL+";"+"filename*=utf-8''"+fileNameURL);
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = response.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(file));
int i = 0;
while ((i = bis.read(buff)) != -1) {
os.write(buff, 0, i);
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 保存源文件
* @param file
* @return
*/
private static String saveOriginalFile(MultipartFile file,String uploadImgUrl,FileOtherKeyParam fileOtherKeyParam,InputStream in) throws Exception{
String md5File = file.getOriginalFilename()+System.currentTimeMillis();
String md5 = MD5Utils.md5(md5File);
String ext = UploadUtil.getExt(file.getOriginalFilename());
StringBuilder str = new StringBuilder();
str.append(uploadImgUrl).append(fileOtherKeyParam.getSource()).append("/").append(fileOtherKeyParam.getModular()).append("/").append(ext).append("/");
UploadUtil.createDir(str.toString());
str.append(md5).append(".").append(ext);
uploadFile(file,str.toString(),in);
return str.toString();
}
public static void uploadFile(MultipartFile mFile, String path,InputStream in) {
try {
byte[] buffer = new byte[1024];
int len = 0;
File file = new File(path);
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();
}
OutputStream out = new FileOutputStream(path);
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void extFile(String ext, MultipartFile file, String fileName,String uploadImgUrl) throws Exception {
switch (ext){
case "doc" :
case "docx":
case "txt":
if (!LicenseUtil.getLicenseWord()) {
System.err.println("破解失败");
}
Document convertDoc = new Document( file.getInputStream());
convertDoc.save(uploadImgUrl+fileName , SaveFormat.PDF);
break;
case "xls" :
case "xlsx":
if (!LicenseUtil.getLicenseExecl()) {
System.err.println("破解失败");
}
Workbook wb = new Workbook( file.getInputStream());// 原始excel路径
wb.save(uploadImgUrl+fileName, com.aspose.cells.SaveFormat.PDF);
break;
case "pptx" :
if (!LicenseUtil.getLicensePPT()) {
System.err.println("破解失败");
}
Presentation pres = new Presentation( file.getInputStream());
pres.save(uploadImgUrl+fileName, com.aspose.slides.SaveFormat.Pdf);
break;
case "jpg" :
case "jpeg" :
case "png":
case "gif":
File file1 = new File(uploadImgUrl + file.getOriginalFilename());
file.transferTo(file1);
imgPdf(uploadImgUrl+fileName,uploadImgUrl+file.getOriginalFilename());
file1.delete();
break;
case "pdf":
File file2 = new File(uploadImgUrl + fileName);
file.transferTo(file2);
break;
default:
System.err.println("不支持此类型");
break;
}
}
/**
* InputStream 转 OutputStream
* @param in
* @return
* @throws Exception
*/
public static ByteArrayOutputStream parse(InputStream in) throws Exception
{
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
int ch;
while ((ch = in.read()) != -1) {
swapStream.write(ch);
}
return swapStream;
}
/**
* 图片转pdf
* @param target
* @param source
* @throws Exception
*/
public static void imgPdf(String target ,String source) throws Exception {
com.itextpdf.text.Document document = new com.itextpdf.text.Document();
//设置文档页边距
document.setMargins(0,0,0,0);
FileOutputStream os = null;
try {
os = new FileOutputStream(target);
PdfWriter.getInstance(document, os);
//打开文档
document.open();
//获取图片的宽高
Image image = Image.getInstance(source);
float imageHeight=image.getScaledHeight();
float imageWidth=image.getScaledWidth();
//设置页面宽高与图片一致
Rectangle rectangle = new Rectangle(imageWidth, imageHeight);
document.setPageSize(rectangle);
//图片居中
image.setAlignment(Image.ALIGN_CENTER);
//新建一页添加图片
document.newPage();
document.add(image);
} catch (Exception ioe) {
System.out.println(ioe.getMessage());
} finally {
//关闭文档
document.close();
try {
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static Configuration config;
static {
config = new Configuration(Configuration.VERSION_2_3_28);
config.setDefaultEncoding("utf-8");
config.setClassForTemplateLoading(ExportUtil.class, "/templates");
}
3.2 使用到的工具包Md5加密
package com.clouderp.fileservice.utils;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Utils {
/**
* 使用md5的算法进行加密
*/
public static String md5(String plainText) {
byte[] secretBytes = null;
try {
secretBytes = MessageDigest.getInstance("md5").digest(plainText.getBytes());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("没有md5这个算法!");
}
String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
// 如果生成数字未满32位,需要前面补0
for (int i = 0; i < 32 - md5code.length(); i++) {
md5code = "0" + md5code;
}
return md5code;
}
/**
* 获取文件的MD5值
*
* @param file
* 目标文件
* @return MD5字符串
* @throws FileNotFoundException
*/
public static String getFileMD5String(File file) throws FileNotFoundException {
MessageDigest digest = null;
byte buffer[] = new byte[8192];
FileInputStream in = new FileInputStream(file);
int len;
try {
digest =MessageDigest.getInstance("MD5");
while ((len = in.read(buffer)) != -1) {
digest.update(buffer, 0, len);
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 获取上传文件的md5
* @param file
* @return
*/
public static String getMd5(MultipartFile file) {
try {
//获取文件的byte信息
byte[] uploadBytes = file.getBytes();
// 拿到一个MD5转换器
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] digest = md5.digest(uploadBytes);
//转换为16进制
return new BigInteger(1, digest).toString(16);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
// 计算文件的 MD5 值
public static String getFileMD5(InputStream in) {
MessageDigest digest = null;
byte buffer[] = new byte[8192];
int len;
try {
digest =MessageDigest.getInstance("MD5");
while ((len = in.read(buffer)) != -1) {
digest.update(buffer, 0, len);
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/***
* MD5加码 生成32位md5码
*/
public static String string2MD5(String inStr){
MessageDigest md5 = null;
try{
md5 = MessageDigest.getInstance("MD5");
}catch (Exception e){
System.out.println(e.toString());
e.printStackTrace();
return "";
}
char[] charArray = inStr.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++){
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
/**
* 加密解密算法 执行一次加密,两次解密
*/
public static String convertMD5(String inStr){
char[] a = inStr.toCharArray();
for (int i = 0; i < a.length; i++){
a[i] = (char) (a[i] ^ 't');
}
String s = new String(a);
return s;
}
public static final String KEY_MAC = "HmacMD5";
/**
* HMAC加密
*
* @param data
* @param key
* @return
* @throws Exception
*/
public static byte[] encryptHMAC(byte[] data, String key) throws Exception {
SecretKey secretKey = new SecretKeySpec(key.getBytes(), KEY_MAC);
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);
return mac.doFinal(data);
}
static String encodeBase64(byte[] source) throws Exception{
return new String(Base64.encodeBase64(source), "UTF-8");
}
/*byte数组转换为HexString*/
public static String byteArrayToHexString(byte[] b) {
StringBuffer sb = new StringBuffer(b.length * 2);
for (int i = 0; i < b.length; i++) {
int v = b[i] & 0xff;
if (v < 16) {
sb.append('0');
}
sb.append(Integer.toHexString(v));
}
return sb.toString();
}
public static String encryptHMAC2String(String data, String key)throws Exception {
byte[] b = encryptHMAC(data.getBytes("UTF-8"), key);
return byteArrayToHexString(b);
}
public String mastKey(String start,String devKey) {
String mastkey="";
/*for(int i=0;i<start.length();i++) {
for(int j=0 ;j<devKey.length();j++) {
char charAt = mastkey.charAt(i);
char charAt2 = devKey.charAt(j);
charAt^charAt2;
}
}*/
return mastkey;
};
}
3.3 上传UploadUtil
package com.clouderp.fileservice.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
public class UploadUtil {
/**
* 构建目录
*
* @param pathdir
* 目录的全路径
* @throws Exception
*/
public static void createDir(String pathdir) throws Exception {
try {
File dir = new File(pathdir);
if (!dir.exists()) {
dir.mkdirs();
}
} catch (Exception e) {
System.err.println(new Date() + ":" + e.getLocalizedMessage());
}
}
/**
* 上传文件*(一般上传)
* @param uploadfile 上传文件流
* @param targetpath 上传后的文件全路径名
* @throws Exception
*/
public static void upload(File uploadfile, String targetpath)
throws Exception {
try {
FileInputStream fin = new FileInputStream(uploadfile);
FileOutputStream fout = new FileOutputStream(targetpath);
byte[] buf = new byte[20480];
int bufsize = 0;
while ((bufsize = fin.read(buf, 0, buf.length)) != -1) {
fout.write(buf, 0, bufsize);
}
fin.close();
fout.close();
} catch (Exception e) {
System.err.println(new Date() + ":" + e.getLocalizedMessage());
}
}
/**
*
* @param tempdir
* @param fileName
* @param in
* @return
* @throws Exception
*/
public static File upload(String tempdir, String fileName, InputStream in)
throws Exception {
File file = new File(tempdir + "/" + fileName);
try {
FileOutputStream fout = new FileOutputStream(file);
byte[] buf = new byte[20480];
int bufsize = 0;
while ((bufsize = in.read(buf, 0, buf.length)) != -1) {
fout.write(buf, 0, bufsize);
}
in.close();
fout.close();
} catch (Exception e) {
System.err.println(new Date() + ":" + e.getLocalizedMessage());
}
return file;
}
/**
* 获得文件后缀
*
* @param filename
* @return
*/
public static String getExt(String filename) {
return filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();
}
/**
* 获得文件名称
*
* @param filename
* @return
*/
public static String getName(String filename) {
return filename.substring(0,filename.lastIndexOf("."));
}
}
3.4 导出工具包ExportUtil
package utils;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import entity.InvoiceExport;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.Cleanup;
import org.apache.commons.lang3.StringUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.util.CollectionUtils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.*;
public class ExportUtil {
private static Configuration config;
static {
config = new Configuration(Configuration.VERSION_2_3_28);
config.setDefaultEncoding("utf-8");
config.setClassForTemplateLoading(ExportUtil.class, "/templates");
}
public static void docFile(HttpServletResponse response, String templateFile, Map<String, Object> dataMap, String fileName) {
try {
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(fileName + ".doc", "UTF-8"))));
Template template = config.getTemplate(templateFile);
File outFile = new File(fileName + ".doc");
@Cleanup BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"));
template.process(dataMap, writer);
@Cleanup FileInputStream inputStream = new FileInputStream(outFile);
byte[] buffer = new byte[512];
int index;
ServletOutputStream outputStream = response.getOutputStream();
while ((index = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, index);
}
} catch (TemplateException | IOException e) {
e.printStackTrace();
}
}
public static void singleXml(InvoiceExport o, HttpServletResponse response, String fileName) {
try {
if (Objects.isNull(o)) {
return;
}
String djh = o.getFpxx().getFpsj().getFp().getDjh();
response.setContentType("application/octet-stream");
response.setCharacterEncoding("gbk");
response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(djh + ".xml", "UTF-8"))));
JAXBContext context = JAXBContext.newInstance(o.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "gbk");
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.setListener(new MarshallerListener());
@Cleanup StringWriter writer = new StringWriter();
writer.append("<?xml version=\"1.0\" encoding=\"GBK\"?>" + "\n ");
marshaller.marshal(o, writer);
response.getWriter().write(writer.toString());
} catch (IOException | JAXBException e) {
e.printStackTrace();
}
}
public static void xmlFile(List<InvoiceExport> o, HttpServletResponse response, String fileName) throws JAXBException, IOException {
response.setContentType("application/octet-stream");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(fileName + ".zip", "UTF-8"))));
if (!CollectionUtils.isEmpty(o)) {
JAXBContext context = JAXBContext.newInstance(o.get(0).getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "gbk");
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.setListener(new MarshallerListener());
LinkedList<File> list = Lists.newLinkedList();
for (InvoiceExport i : o) {
@Cleanup StringWriter writer = new StringWriter();
writer.append("<?xml version=\"1.0\" encoding=\"GBK\"?>" + "\n ");
marshaller.marshal(i, writer);
String djh = i.getFpxx().getFpsj().getFp().getDjh();
File file = strToFile(writer.toString(), djh + ".xml");
list.add(file);
}
zipFile(list, response);
}
}
static class MarshallerListener extends Marshaller.Listener {
@Override
public void beforeMarshal(Object source) {
super.beforeMarshal(source);
Field[] fields = source.getClass().getDeclaredFields();
Arrays.stream(fields).forEach(f -> {
f.setAccessible(true);
try {
if (f.getType() == String.class && f.get(source) == null) {
f.set(source, StringUtils.EMPTY);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
});
}
}
private static File strToFile(String text, String fileName) throws IOException {
if (StringUtils.isEmpty(text)) {
return null;
}
File file = new File(fileName);
try {
Files.write(text.getBytes(), file);
}catch (IOException e){
e.printStackTrace();
}
return file;
}
private static void zipFile(List<File> files, HttpServletResponse response) throws IOException {
byte[] bytes = new byte[1024];
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(response.getOutputStream());
zos.setEncoding("utf-8");
String serverName = System.getProperty("os.name");
String separator = System.getProperty("file.separator");
boolean linuxOS = StringUtils.equals("Linux", serverName) || StringUtils.equals("/", separator);
for (File file : files) {
ZipEntry entry = new ZipEntry(file.getName());
zos.putNextEntry(entry);
@Cleanup FileInputStream in = new FileInputStream(file);
int len;
if (linuxOS) {
entry.setUnixMode(644);
}
while ((len = in.read(bytes)) > 0) {
zos.write(bytes, 0, len);
}
zos.closeEntry();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (Objects.nonNull(zos)) {
try {
zos.flush();
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
files.forEach(f -> f.delete());
}
}
}
}
4.设置文件上传大小及个数
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 单个数据大小
factory.setMaxFileSize(DataSize.ofMegabytes(20)); // MB
// 总上传数据大小
factory.setMaxRequestSize(DataSize.ofMegabytes(100));
return factory.createMultipartConfig();
}
5.如果需要预览 当前存储方式为 源文件一份 源文件转pdf文件一份 pdf预览直接通过地址预览
更多推荐
已为社区贡献2条内容
所有评论(0)