1. 话不多说直接上代码:
/**
* 将文件保存至本地
*
* @author colin
*/
public class MultipartFileUtil {
private static final FileConfigDTO fileDto = SpringUtils.getBean(FileConfigDTO.class);
/**
* @param file 文件
* @param folderName 文件夹名称
* @return 文件的存储的绝对路径
*/
public static String saveMultipartFile(MultipartFile file, String folderName) {
String targetDirPath = fileDto.getUploadsPath() + folderName;
File toFile = null;
if (file.equals("") || file.getSize() <= 0) {
return null;
} else {
/*获取文件原名称*/
String originalFilename = file.getOriginalFilename();
/*获取文件格式*/
assert originalFilename != null;
String fileFormat = originalFilename.substring(originalFilename.lastIndexOf("."));
toFile = new File(targetDirPath + File.separator + originalFilename.substring(0, originalFilename.lastIndexOf(".")) + fileFormat);
String absolutePath = null;
try {
absolutePath = toFile.getCanonicalPath();
/*判断路径中的文件夹是否存在,如果不存在,先创建文件夹*/
String dirPath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
File dir = new File(dirPath);
if (!dir.exists()) {
dir.mkdirs();
}
InputStream ins = file.getInputStream();
inputStreamToFile(ins, toFile);
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
return absolutePath;
}
}
//获取流文件
private static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = Files.newOutputStream(file.toPath());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. 欢迎交流:
🐧🐧: 1745957645