import com.sitech.cmap.process.engine.app.exception.BusinessException;
import com.sitech.cmap.process.engine.app.exception.ErrorCodeEnum;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
public class test {
public static Map<String, Object> upload(String uploadPath, MultipartFile file) {
HashMap<String, Object> responseMap = new HashMap<>();
if(file.getSize() > 1024 * 1024 * 5) {
responseMap.put("code", 500);
responseMap.put("msg", "文件过大,请上传5M以内的文件。");
return responseMap;
}
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
if(!"png".equals(suffix) || !"jpg".equals(suffix)) {
responseMap.put("code", 500);
responseMap.put("msg", "文件格式不正确!只能上传.png/.jpg格式文件。");
return responseMap;
}
/**
* 存储空间 这里存储上传文件的文件夹按照年月日分类。
*/
String BUCKET = uploadPath + new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime()) + "/";
// 拼接文件路径
String storagePath = BUCKET + "/" + file.getOriginalFilename();
//如果文件夹不存在则创建
Path directoryFilePath = Paths.get(BUCKET);
if (!Files.isDirectory(directoryFilePath, LinkOption.NOFOLLOW_LINKS) && !Files.exists(directoryFilePath, LinkOption.NOFOLLOW_LINKS)) {
try {
//创建多层目录用这个方法,用Files.createDirectory方法只能创建一层目录。
Files.createDirectories(directoryFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
//判断文件是否存在,存在先删除文件。
Path path = Paths.get(storagePath);
if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
try {
Files.delete(path);
} catch (IOException e) {
e.printStackTrace();
}
}
//这里使用了 try-with-resource 语法,该语句确保了每个资源,在语句结束时关闭。try块退出时,会自动调用res.close()方法,关闭资源。
//try-with-resource中的代码一般放的是对资源的申请,如果{}中的代码出项了异常,()中的资源就会被关闭,这在inputstream和outputstream的使用中会很方便。
try (
// JDK8 TWR 不能关闭外部资源的,参数传进来的inputStream属于外部资源,我这里定义一个内部的变量来接收这个外部的流。从而达到关闭外部流的效果。
InputStream innerInputStream = file.getInputStream();
FileOutputStream outputStream = new FileOutputStream(new File(storagePath))
) {
// 拷贝缓冲区
byte[] buffer = new byte[1024];
// 读取文件流长度
int len;
// 循环读取inputStream中数据写入到outputStream
while ((len = innerInputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
// 冲刷流
outputStream.flush();
} catch (Exception e) {
System.out.println("文件上传失败!");
throw new BusinessException(ErrorCodeEnum.FILE_UPLOAD_FAILURE, e);
}
return responseMap;
}
}
文件上传方法
最新推荐文章于 2024-04-19 15:34:48 发布