Springboot jar包上传图片获取静态资源路径

1、增加过滤配置

package com.XXX.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


@Configuration
public class PathConfig extends WebMvcConfigurerAdapter{
    //将jar文件下的对应静态资源文件路径对应到磁盘的路径(根据个人的情况修改"file:static/"的static的值
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.
                addResourceHandler("/static/**"). addResourceLocations("classpath:/static/","file:static/");
    }

}

2、配置yml

spring:
  resources:
    static-locations: classpath:static/,file:${jar.fileUrl}

# file配置(jar和fileUrl自己随意定义)
jar:
  fileUrl: D:/XXX/XXX/upload/static

3、具体实现

@PostMapping("/upload")
    public String upload(MultipartFile image,String username,HttpSession session) throws Exception {
	//主要是这句,获得路径,上传的图片存放在D:/XXX/XXX/upload/static/static下
        String  destDir=session.getServletContext().getRealPath("static/");
        InputStream is = image.getInputStream();//输入流
        BufferedImage bufferedImg = ImageIO.read(is);
        int width = bufferedImg.getWidth();//获取图片宽高
        int height = bufferedImg.getHeight();
        User user = userService.checkUsername(username);
        if (user ==null){
            if (width<=500 && height<=500){
                saveOrUpdateUserImageFile(image,username,destDir);
                return "头像ok";
            }else{
                return "请上传分辨率宽<500,高<500的图片";
            }
        }else {
            return "用户名已被注册";
        }
    }
    public String saveOrUpdateUserImageFile(MultipartFile image,String username,String destDir)
            throws IOException {
        File imageFolder= new File(destDir);
        String imageName = username+".jpg";
        File file = new File(imageFolder,imageName);
        System.out.println(file);
        if(!file.getParentFile().exists())
            file.getParentFile().mkdirs();
        image.transferTo(file);
        BufferedImage img = ImageUtil.change2jpg(file);
        ImageIO.write(img, "jpg", file);
        return imageName;
    }

参考文章

  • 作者:seibert(联系作者)
  • 发表时间:2020-06
  • 版权声明:未经站长允许,不可转载
  • 公众号转载:请在文末添加作者公众号二维码
  • 评论