@Slf4j
@Component
public class MultipartFileUtil {
private final static Integer FILE_SIZE = 5;//文件上傳限制大小
private final static String FILE_UNIT = "M";//文件上傳限制單位(B,K,M,G)
/**
* @param len 文件長度
* @param size 限制大小
* @param unit 限制單位(B,K,M,G)
* @描述 判斷文件大小
*/
public static boolean checkFileSize(Long len, int size, String unit) {
double fileSize = 0;
if ("B".equalsIgnoreCase(unit)) {
fileSize = (double) len;
} else if ("K".equalsIgnoreCase(unit)) {
fileSize = (double) len / 1024;
} else if ("M".equalsIgnoreCase(unit)) {
fileSize = (double) len / 1048576;
} else if ("G".equalsIgnoreCase(unit)) {
fileSize = (double) len / 1073741824;
}
return !(fileSize > size);
}
//文件上傳調(diào)用
public static String upload(MultipartFile file) {
boolean flag = checkFileSize(file.getSize(), FILE_SIZE, FILE_UNIT);
if (!flag) {
throw new RuntimeException("上傳文件大小超出限制");
}
}
}
PS:以上基礎(chǔ)需要項目本身設(shè)定好最大文件閾值友浸,在閾值的基礎(chǔ)上進(jìn)行限制大小提示拆又,如果不設(shè)置梢杭,文件上傳大小默認(rèn)1MB温兼,超出則拋異常
#設(shè)置單個文件最大請求100MB,最多一次請求2個文件(具體設(shè)定看自己需求)
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=200MB
#設(shè)置文件上傳大小不進(jìn)行限制
spring.servlet.multipart.max-file-size=-1
spring.servlet.multipart.max-request-size=-1
/**
* @描述 文件下載
* @參數(shù) [response, filePath, filename]
* @返回值 javax.servlet.http.HttpServletResponse
* @創(chuàng)建時間 2021/6/29
*/
public static void download(HttpServletResponse response, String filePath, String filename) {
try {
// path是指欲下載的文件的路徑
File file = new File(filePath);
// 以流的形式下載文件
InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 設(shè)置response的Header
response.setContentType("application/octet-stream; charset=UTF-8");
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}