FileUtils.java
package com.june.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;
public class FileUtils {
private FileUtils() {}
/**
* 下载文件
* @param response
* @param fileDirPath 文件保存目录路径
* @param fileName 文件名
*/
public static void download(HttpServletResponse response, String fileDirPath, String fileName)
throws Exception {
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\""
+ URLEncoder.encode(fileName, "UTF-8") + "\"");
response.setContentType("application/octet-stream; charset=UTF-8");
File file = new File(getRealPath(fileDirPath), fileName);
InputStream is = new FileInputStream(file);
OutputStream os = response.getOutputStream();
byte[] data = IOUtils.toByteArray(is);
IOUtils.closeQuietly(is);
response.setHeader("Content-Length", "" + data.length);
IOUtils.write(data, os);
IOUtils.closeQuietly(os);
}
/**
* 上传文件
* @param file 文件
* @param dirPath 文件所在目录路径
*/
public static void upload(MultipartFile file, String dirPath)
throws Exception {
String fileName = file.getOriginalFilename();
String realDirPath = getRealPath(dirPath) + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
File dir = new File(realDirPath);
//判断上传目录是否存在,若不存在则创建
if (!dir.exists()) {
dir.mkdir();
}
StringBuilder filePath = new StringBuilder();
filePath.append(realDirPath)
.append(File.separator)
.append(System.currentTimeMillis())
.append(fileName.substring(fileName.indexOf('.')));
InputStream is = file.getInputStream();
OutputStream os = new FileOutputStream(filePath.toString());
IOUtils.copy(is, os);
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}
/**
* 根据文件classpath路径获取真实路径
* @param path classpath下的路径
* @return 真实路径
*/
public static String getRealPath(String path) {
return FileUtils.class.getResource(path).getPath();
}
}