一、概述
调用第一个接口时,先将多张图片存到本地;再调用第二个接口,将图片统一上传到图片服务器上。
二、应用场景
根据类别,上传多张图片
三、代码实现
1、controller层
@ApiOperation("临时上传图片")
@PostMapping("/img/temp")
public JsonResult uploadFileBufferToLocal(@NotNull @RequestParam @ApiParam("图片所属种类)") String photoType,
@NotNull @Image @ApiParam("不超过10M,请上传jpg和png文件") MultipartFile file) {
return service.uploadFileBufferToLocal(photoType, file);
}
@ApiOperation("上传照片")
@PostMapping("/upload")
public JsonResult upload(@NotNull @RequestParam @ApiParam("图片类别") Integer type) {
return service.upload(type);
}
2、serviceImpl层
缓存到本地的功能实现
public JsonResult uploadFileBufferToLocal(String photoType, MultipartFile file) {
//将文件缓存到本地
MultipartFile localFile = createLocalFile(photoType, file);
if (localFile == null) {
log.error("Create local file failed!");
return JsonResult.faild("Create local file failed!");
}
log.info("Create local file successfully");
return JsonResult.success("Create local file successfully");
}
/**
* 通过上传的文件名,缓冲到本地,后面才能解压、验证
*
* @param photoType 图片类型
* @param file
*/
public MultipartFile createLocalFile(String photoType, MultipartFile file) {
String filePath = "C:/upload/temp/";
File localFile = new File(filePath);
//先创建目录
localFile.mkdirs();
String originalFilename = file.getOriginalFilename();
if (originalFilename.contains(",")) {
originalFilename = originalFilename.replace(",", "");
}
if (originalFilename.contains(" ")) {
originalFilename = originalFilename.replace(" ", "");
}
String newname = photoType + "_" + originalFilename;
String path = filePath + "/" + newname;
log.info("createLocalFile path = {}", path);
localFile = new File(path);
FileOutputStream fos = null;
InputStream in = null;
try {
if (localFile.exists()) {
//如果文件存在删除文件
boolean delete = localFile.delete();
if (delete == false) {
log.error("Delete exist file \"{}\" failed!!!", path, new Exception("Delete exist file \"" + path + "\" failed!!!"));
}
}
//创建文件
if (!localFile.exists()) {
//如果文件不存在,则创建新的文件
localFile.createNewFile();
log.info("Create file successfully,the file is {}", path);
}
//创建文件成功后,写入内容到文件里
fos = new FileOutputStream(localFile);
in = file.getInputStream();
byte[] bytes = new byte[1024];
int len = -1;
while ((len = in.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
FileInputStream fileInputStream = new FileInputStream(localFile);
MultipartFile multipartFile = new MockMultipartFile(localFile.getName(), localFile.getName(),
ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
fos.flush();
log.info("Reading uploaded file and buffering to local successfully!");
return multipartFile;
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
if (fos != null) {
fos.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
log.error("InputStream or OutputStream close error : {}", e);
return null;
}
}
}
上传到服务器的功能实现
public JsonResult upload(Integer type) {
String filepath = "C:/upload/temp/";
File localFile = new File(filepath);//File类型可以是文件也可以是文件夹
File[] files = localFile.listFiles();//将该目录下的所有文件放置在一个File类型的数组中
QueryWrapper<Entity> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("type", type);
Entity entity = entityDao.selectOne(queryWrapper);
String result = "";
try {
for (int i = 0; i < files.length; i++) {
InputStream inputStream = new FileInputStream(files[i]);
MultipartFile multipartFile = new MockMultipartFile(files[i].getName(), inputStream);
/*处理传入文件名中的空格及逗号*/
String originalFilename = multipartFile.getName();
InputStreamResource isr = new InputStreamResource(multipartFile.getInputStream(),
originalFilename);
Map<String, Object> params = new HashMap<>();
params.put("file", isr);
params.put("path", idWorkerUtil.nextId());
params.put("output", "json");
params.put("auth_token", fastdfsAuthCode);
//上传图片到gofastdfs服务器
result = HttpUtil.post(uploadUrl, params);
//删除本地文件
files[i].delete();
entityDao.updateById(entity);
}
} catch (IOException e) {
log.error("错误为=" + e.getMessage(), e);
}
return JsonResult.success();
}
四、感谢
本文中的本地文件储存来源博主的这篇文章,https://blog.csdn.net/weixin_30462049/article/details/97326852,欢迎大家移驾交流学习。