1、将传统的IO流改为NIO
/**
*
* Title: upload
* Description: 上传文件
* @param file
* @param licenseType
* @param realName
* @see IOcrUploadFileService#upload(MultipartFile, String, String)
*/
@Override
@Transactional
public Long upload(MultipartFile file, String licenseType, String realName) {
checkFile(file, licenseType);
// 写入数据库
String fileName = file.getOriginalFilename();
String zipNameSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
String zipName = fileName.substring(0, fileName.lastIndexOf("."));
Long id = ocrUploadFileDao.save(licenseType.trim(), zipName, zipNameSuffix, realName);
FileInputStream in = null;
FileOutputStream out = null;
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
in = (FileInputStream) file.getInputStream();
// 创建目录
File rootFile = new File(rootDirectory);
if (!rootFile.exists()) {// 如果文件夹不存在
rootFile.mkdir();// 创建文件夹
}
File zipFile = new File(rootFile, fileName);
out = new FileOutputStream(zipFile);
inChannel = in.getChannel();
outChannel = out.getChannel();
// 分配指定大小缓存区
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 将通道中的数据缓冲区中
while (inChannel.read(buffer) != -1) {
buffer.flip();// 切换成读数据模式
// 将缓冲区中的数据写入通道中
outChannel.write(buffer);
buffer.clear();// 清空缓冲区
}
} catch (IOException e) {
logger.error("uploadFile has error:{}", e);
throw new BusinessException(10005, "上传文件异常");
} finally {
try {
if (outChannel != null) {
outChannel.close();
}
if (out != null) {
out.close();
}
if (inChannel != null) {
inChannel.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return id;
}
2、如果上传文件过大,导致内存溢出,那么就需要修改JVM参数:Xmx(JVM最大的堆内存大小)