Java图片上传实现方式
例举 MultipartFile 处理图片上传方式
2021年8月3日
核心代码块
public Result uploadImg(MultipartFile multipartFile, String imgKey) {
if (imgKey == null) {
return Result.error("缺失 imgKey !");
}
WxBackgroundDto wxBackgroundDto = new WxBackgroundDto();
try {
wxBackgroundDto.setImgKey(imgKey);
wxBackgroundDto.setImgData(multipartFile.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
// 存入
if (wxBackgroundDto != null) {
QueryWrapper queryWrapper = new QueryWrapper();
queryWrapper.eq("img_key", imgKey);
wxBackgroundMapper.delete(queryWrapper);
int result = wxBackgroundMapper.insert(wxBackgroundDto);
if (result == 1) {
return Result.ok();
} else {
return Result.error("写入失败");
}
} else {
return Result.ok() ;
}
}
讲解 MultipartFile
MultipartFile是SpringMVC提供简化上传操作的工具类。
在不使用框架之前,都是使用原生的 HttpServletRequest 来接收上传的数据,文件是以二进制流传递到后端的,然后需要我们自己转换为 File 类。使用了 MultipartFile 工具类之后,我们对文件上传的操作就简便许多了。
public interface MultipartFile extends InputStreamSource {
String getName();
@Nullable
String getOriginalFilename();
@Nullable
String getContentType();
boolean isEmpty();
long getSize();
byte[] getBytes() throws IOException;
InputStream getInputStream() throws IOException;
default Resource getResource() {
return new MultipartFileResource(this);
}
void transferTo(File var1) throws IOException, IllegalStateException;
default void transferTo(Path dest) throws IOException, IllegalStateException {
FileCopyUtils.copy(this.getInputStream(), Files.newOutputStream(dest));
}
}
InputStreamSource 这个接口本质上返回的还是一个 InputStream 流对象