最近的一个项目做了个上传图片的功能,特此记录下踩坑经历!
一、配置yml,为了方便后续维护,所以在yml中配置存放和映射的地址
二、添加虚拟路径映射配置(此步是关键)
@Configuration
public class URLConfig implements WebMvcConfigurer {
@Value("${pictureFile.path}")
private String picturePath;
@Value("${pictureFile.path-mapping}")
private String picturePath_mapping;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(picturePath_mapping+"**").addResourceLocations("file:"+picturePath);
}
}
三、图片上传工具类
package com.xcj.weixin.util;
import com.xcj.weixin.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
@Component
public class UploadUtil {
@Value("${pictureFile.path}")
private String picturePath;
@Value("${pictureFile.path-mapping}")
private String picturePathMapping;
public ResultVO ImgUpload(MultipartFile file) throws IOException {
ResultVO resultVO = new ResultVO();
//判断图片后缀是否为.jpg
String fileNameSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
if(!fileNameSuffix.equals(".jpg")){
resultVO.setMsg("图片后缀名必须为jpg!");
resultVO.setCode(400);
return resultVO;
}
/*判断文件上传路径是否存在,不存在则创建*/
File filePath = new File(picturePath);
if (!filePath.exists()) {
filePath.mkdirs();
}
/*判断上传文件是否大于一兆*/
if (file.getSize() > 1204 * 1024) {
String msg = "上传文件大于1兆,上传失败!";
resultVO.setMsg(msg);
resultVO.setCode(400);
return resultVO;
}
/*创建上传文件的名字*/
String pictureName = MyRandomUtil.getPictureName()+fileNameSuffix;
/*拼接文件名和路径,(即将要被创建的文件)*/
File myfile = new File(filePath, pictureName);
//转移
file.transferTo(myfile);
resultVO.setMsg("success,上传成功!");
resultVO.setCode(200);
//数据库存放的图片路径(是映射路径开头)
String fileName = picturePathMapping+pictureName;
resultVO.setData(fileName);
return resultVO;
}
}
四、service中调用
ResultVO resultVO = null;
try {
resultVO = uploadUtil.ImgUpload(file);
//更新数据库数据
if (resultVO.getCode() == 200) {
productMapper.updateProduct2(dto, resultVO.getData().toString());
}
} catch (IOException e) {
e.printStackTrace();
}
总结:
关键在于理解、配置虚拟路径,即将实际的存放图片的路径映射成虚拟的路径,
对应该项目就是:将 " D:/myimgs/ " 映射成 " /myimgs/ "。