使用spring boot上传图片

技术栈:

SpringBoot+mybatis+mysql+freemarker

  之前将图片存储在项目的路径中,导致每次上传后都需要重新编译才能读出图片,查阅相关资料后发现,图片需要单独的路径进行存储,并对路径进行配置。

controller:

    @RequestMapping(value = "uploadImg",method = RequestMethod.POST)
    public ResultWrapper uploadImg(@RequestParam(value = "file",required = false) MultipartFile file){
        return iResBaseInfoService.uploadImg(file);
    }

service:

  @Value("${absoluteImgPath}")
    String absoluteImgPath;

    @Value("${sonImgPath}")
    String sonImgPath;

    @Value("${server.port}")
    String port;

    @Override
    public ResultWrapper uploadImg(MultipartFile file) {

        if(file.isEmpty()){
            return ResultWrapper.fail("图片不能为空");
        }
        String originalFilename = file.getOriginalFilename();
        //随机生成文件名
        String fileName = UUID.randomUUID() + originalFilename;
        File dest = new File(absoluteImgPath + fileName);
        String imgUrl = sonImgPath +fileName;
		//如果文件夹不存在,就创建新的文件夹
        if(!dest.getParentFile().exists()){
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultWrapper.success(imgUrl);
    }

随机数生成: 可选,可以使用UUID


public class RandomUtils {

    private static final String charlist = "0123456789";

    public static String createRandomString(int len) {
        String str = new String();
        for (int i = 0; i < len; i++) {
            str += charlist.charAt(getRandom(charlist.length()));
        }
        return str;
    }

    public static int getRandom(int mod) {
        if (mod < 1) {
            return 0;
        }
        int ret = getInt() % mod;
        return ret;
    }

    private static int getInt() {
        int ret = Math.abs(Long.valueOf(getRandomNumString()).intValue());
        return ret;
    }

    private static String getRandomNumString() {
        double d = Math.random();
        String dStr = String.valueOf(d).replaceAll("[^\\d]", "");
        if (dStr.length() > 1) {
            dStr = dStr.substring(0, dStr.length() - 1);
        }
        return dStr;
    }
}
application.properties:

absoluteImgPath = 自己的路径
sonImgPath = /images/

路径配置:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Value("${absoluteImgPath}")
    String absoluteImgPath;

    @Value("${sonImgPath}")
    String sonImgPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/web/images/");
        registry.addResourceHandler(sonImgPath + "**").addResourceLocations("file:"+absoluteImgPath);
    }
}

数据库存储的url形式:

/images/9045969040S90.jpg
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页