top.doudou.common.tool.file.UploadFileUtils Maven / Gradle / Ivy
package top.doudou.common.tool.file;
import cn.hutool.core.io.FileUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import top.doudou.base.exception.ServeException;
import top.doudou.base.stream.StreamCloseUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.Calendar;
import java.util.UUID;
/**
* @Description 文件上传与下载工具类
* @Author 傻男人 <[email protected]>
* @Date 2020-09-30 10:33
* @Version V1.0
*/
public class UploadFileUtils {
/**
* 上传文件
* @param file 上传的文件
* @param basePath 上传的路径
* @param flag 是否采用原始的文件名命名上传的文件(true 原文件名 false uuid的文件名)
* @return
* @throws IOException
*/
public static File uploadByTransferTo(MultipartFile file,String basePath,boolean flag) throws IOException {
long startTime = System.currentTimeMillis();
File newFile = null;
if(flag){
newFile = new File(getPath(basePath)+file.getOriginalFilename());
}else {
newFile = new File(getPath(basePath)+ getUUIDFileName(file));
}
if(!newFile.exists()){
FileUtil.touch(newFile);
}
file.transferTo(newFile);
long endTime = System.currentTimeMillis();
System.out.println("采用file.Transto的运行时间:" + String.valueOf(endTime - startTime) + "ms");
return newFile;
}
public static Integer uploadByTransferTo(MultipartFile[] files,String path,boolean flag) throws IOException{
for (MultipartFile file: files){
uploadByTransferTo(file, path, flag);
}
return files.length;
}
/**
* 上传文件(流的方式)
* @param basePath 基础路径
* @param file 上传的文件
* @return
*/
public File uploadByStream(MultipartFile file,String basePath){
long startTime = System.currentTimeMillis();
String fileName= getPath(basePath)+ getUUIDFileName(file);
File tempFile=new File(fileName);
try {
FileUtils.writeByteArrayToFile(tempFile,file.getBytes());
}catch (IOException e){
e.printStackTrace();
throw new ServeException("文件上传失败");
}
long endTime = System.currentTimeMillis();
System.out.println("采用uploadByStream的运行时间:" + String.valueOf(endTime - startTime) + "ms");
return tempFile;
}
private static String getUUIDFileName(MultipartFile file){
return UUID.randomUUID().toString()+"."+ MultipartFileUtils.getFileType(file);
}
private static String getPath(String basePath) {
StringBuilder sb = new StringBuilder();
sb.append("/");
if(StringUtils.isNotBlank(basePath)){
sb.append(basePath+"/");
}
Calendar calendar = Calendar.getInstance();
sb.append(calendar.get(Calendar.YEAR)).append("/");
sb.append(calendar.get(Calendar.MONTH) + 1).append("/");
sb.append(calendar.get(Calendar.DATE)).append("/");
return sb.toString();
}
/**
* 文件下载
* @param filePath file路径
* @param response 响应
* @param isOnLine 是否在线打开
* @throws Exception
*/
public static void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
byte[] buf = new byte[1024];
int len = 0;
response.reset(); // 非常重要
if (isOnLine) {
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename=" + file.getName());
// 文件名应该编码成UTF-8
} else { // 纯下载方式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}
/**
* 下载文件
* @param response
* @param filePath
* @param newFileName 下载文件的文件名(如果为null 则用原文件名)
* @throws IOException
*/
public static void downLoad(HttpServletResponse response, String filePath,String newFileName) throws IOException {
File file = new File(filePath);
if (!file.exists()) {
response.sendError(404, "File not found!");
return;
}
FileInputStream fileInputStream = null;
OutputStream os = null;
try {
fileInputStream = new FileInputStream(file);
response.reset();
String realFileName = null;
if(StringUtils.isNotEmpty(newFileName)){
realFileName = new String((newFileName+"."+ FileUtil.getSuffix(file)).getBytes("UTF-8"), "ISO-8859-1");
}else {
realFileName = new String(file.getName().getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-disposition", "attachment; filename=" + realFileName);
response.setContentType("application/octet-stream");
byte[] bytes = new byte[1024];
os = response.getOutputStream();
int len = 0;
while ((len = fileInputStream.read(bytes)) > 0)
os.write(bytes, 0, len);
os.close();
return;
} catch (IOException e) {
e.printStackTrace();
}finally {
StreamCloseUtils.close(fileInputStream);
StreamCloseUtils.close(os);
}
}
public void downLoad(HttpServletResponse response, String filePath) throws IOException {
downLoad(response,filePath,null);
}
}