Java MultipartFile 上传文件/上传图片
1. 判断允许上传文件的 文件后缀/图片后缀/相片后缀 和 其它工具类
import org.springframework.stereotype.Component;
import java.io.File;
import java.util.Arrays;
import java.util.List;
@Component
public class FileUtil {
public static final List<String> IMAGE_EXTENSIONS = Arrays.asList(".jpg", ".jpeg", ".png");
}
import java.util.UUID;
public class CommonUtil {
public static String getUUID() {
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
return uuid;
}
}
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateUtil {
public static final String HH = "HH";
public static final String YYYY_MM_DD = "yyyy-MM-dd";
public static final DateTimeFormatter FORMATTER_HH = DateTimeFormatter.ofPattern(HH);
public static final DateTimeFormatter FORMATTER_YYYY_MM_DD = DateTimeFormatter.ofPattern(YYYY_MM_DD);
public static String getHH() {
return FORMATTER_HH.format(LocalDateTime.now());
}
public static String getYYYYMMDD() {
return FORMATTER_YYYY_MM_DD.format(LocalDateTime.now());
}
}
2. 上传接口
@PostMapping("/updateImage.do")
public Map<String, String> updateImage(@RequestParam("image") MultipartFile[] multfiles) {
Map<String, String> result = new HashMap<>();
if (multfiles.length == 0) {
result.put("message", "请选择图片!");
return result;
}
// 源文件名称
final String originalFileName = multfiles[0].getOriginalFilename();
if (StringUtils.isBlank(originalFileName)) {
result.put("message", "请选择图片!");
return result;
}
// 文件后缀[.jpg]
final String suffix = originalFileName.substring(originalFileName.lastIndexOf(".")).toLowerCase();
if (!FileUtil.IMAGE_EXTENSIONS.contains(suffix)) {
result.put("message", "图片格式错误!");
return result;
}
String lastFilePath;
String newFileName = CommonUtil.getUUID() + suffix;
String folderName = File.separator + "temp" + File.separator;
String relativePath = folderName + DateUtil.getYYYYMMDD() + File.separator + DateUtil.getHH();
String filePath = "D:\\file" + relativePath;
String fileUrl = null;
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream out = null;
try {
lastFilePath = filePath + File.separator + newFileName;
out = new FileOutputStream(lastFilePath);
out.write(multfiles[0].getBytes());
fileUrl = "http://127.0.0.1:9000" + relativePath + File.separator + newFileName;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (fileUrl == null) {
result.put("message", "图片上传失败!");
return result;
}
result.put("message", "上传成功!");
result.put("url", fileUrl);
return result;
}
3. 上传成功
url => http://127.0.0.1:9000/temp/2019-09-12/14/0eac00b96f134652b34172e84febe8d1.jpg
如果您觉得有帮助,欢迎点赞哦 ~ 谢谢!!