springboot accesses local images with http requests

As shown in the figure below, the pictures stored on the machine (server) want to be accessed through the URL address on the browser:
insert image description here

1. Upload

The implementation is very simple, just use the interceptor to map the local address to the url path:

@Configuration
public class FilePathConfig implements WebMvcConfigurer {
    
    
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    
    
        registry.addResourceHandler("/upload/**") //虚拟url路径
                .addResourceLocations("file:E:/image/"); //真实本地路径
    }
}

Start the program, enter the local Ip+port+Url path (replacing the local path of the image)+image file name:
insert image description here
try to upload and then visit:

 public static final String host = "http://127.0.0.1:8080/upload/";


    @ApiOperation(value = "上传图片")
    @ApiImplicitParam(name = "file",value = "图片上传",required = true,dataTypeClass = MultipartFile.class,
            allowMultiple = true,paramType = "query")
    @PostMapping(value = "/upload")
    @ResponseBody
    public String insertOrderImg(@RequestParam("file") MultipartFile file) {
    
    
        // 文件上传路径
        String location = "E:\\image\\";

        String originalFilename = file.getOriginalFilename();
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //设置允许上传文件类型
        String suffixList = ".jpg,.png,.ico,.bmp,.jpeg";
        String imgUrl=null;
        // 判断是否包含
        if (suffixList.contains(extName.trim().toLowerCase())) {
    
    
            // 保存文件的路径
            String path = location + originalFilename;
            //  spring的transferTo保存文件方法
            try {
    
    
                file.transferTo(new File(path));
                imgUrl = host + originalFilename;
            } catch (IOException e) {
    
    
                log.info("保存失败");
            }
        }
        return imgUrl;
    }

Use knife4j to upload the picture successfully and return the url address:
insert image description here
insert image description here

2. Compression

Use Hutool or Thumbnails
to introduce dependencies

<!--        图像处理依赖,包含了Thumbnails-->
        <dependency>
            <groupId>com.siashan</groupId>
            <artifactId>toolkit-image</artifactId>
            <version>1.1.1</version>
        </dependency>
public static final String host = "http://127.0.0.1:8080/upload/";


    @ApiOperation(value = "上传图片")
    @ApiImplicitParam(name = "file",value = "图片上传",required = true,dataTypeClass = MultipartFile.class,
            allowMultiple = true,paramType = "query")
    @PostMapping(value = "/upload")
    @ResponseBody
    public String insertOrderImg(@RequestParam("file") MultipartFile file) throws IOException {
    
    
        // 文件上传路径
        String location = "E:\\image\\";
        String originalFilename = file.getOriginalFilename();
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //设置允许上传文件类型
        String suffixList = ".jpg,.png,.ico,.bmp,.jpeg";
        String imgUrl=null;
        // 判断是否包含
        if (suffixList.contains(extName.trim().toLowerCase())) {
    
    
            BufferedImage image = ImgUtil.read(file.getInputStream());
            int height = image.getHeight();
            int width = image.getWidth();
            // 保存文件的路径
            String path = location + originalFilename;
            // thumbnailator压缩存放路径
            String thumbPath= location+"thumbnailator"+originalFilename;
            //Img压缩存放路径
            String imgPath = location +"img"+ originalFilename;
            String newPath = location +"new"+ originalFilename;
            String shaValue = DigestUtil.sha256Hex(file.getBytes());
            //  spring的transferTo保存文件方法
            try {
    
    
                log.info("原图高{},宽{},大小{}KB",height,width,file.getSize()/1024);
                file.transferTo(new File(path));

                //Hutool图像编辑器压缩
                Img img = Img.from(file.getInputStream());
                Image img1 = img.scale(0.5f).setQuality(0.2f).getImg();
                byte[] bytes = ImgUtil.toBytes(img1, ImgUtil.IMAGE_TYPE_JPEG);
                log.info("Hutool压缩后高{},宽{},大小{}KB",img1.getHeight(null),img1.getWidth(null),bytes.length/1024);
                FileUtil.writeBytes(bytes,imgPath);

                //Thumbnails压缩 要读取压缩后图片大小和尺寸必须写后再读,没有Img编辑器压缩方便
                OutputStream outputStream1 = new FileOutputStream(thumbPath);
                Thumbnails.of(file.getInputStream())
                        .scale(0.5f)
                        .outputQuality(0.2f)
                        .toOutputStream(outputStream1);
                outputStream1.close();
                byte[] bytes1 = FileUtil.readBytes(thumbPath);
                BufferedImage read1 = ImgUtil.read(thumbPath);
                log.info("直接压缩高{},宽{},大小{}KB",read1.getHeight(),read1.getWidth(),bytes1.length/1024);

//                //Hutool另一种压缩方法,要读取压缩后图片大小和尺寸必须写后再读 ,没有Img编辑器压缩方便
//                OutputStream outputStream2 = new FileOutputStream(newPath);
//                ImageOutputStream imageOutputStream = ImgUtil.getImageOutputStream(outputStream2);
//                ImgUtil.scale(image, imageOutputStream, 0.5f);
//                ImgUtil.write(image,ImgUtil.IMAGE_TYPE_JPG,imageOutputStream,0.2F);
//                outputStream2.close();
//                byte[] bytes2 = FileUtil.readBytes(newPath);
//                BufferedImage read2 = ImgUtil.read(newPath);
//                log.info("Hutool直接压缩高{},宽{},大小{}KB",read2.getHeight(),read2.getWidth(),bytes2.length/1024);
                imgUrl = host + originalFilename;
            } catch (IOException e) {
    
    
                log.info("保存失败");
            }
        }
        return imgUrl;
    }

insert image description here
insert image description here

3. Duplication of the same picture is prohibited

insert image description here

 public static final String host = "http://127.0.0.1:8080/upload/";

    public static final Map<String,String> imgMap= new ConcurrentHashMap<>();

    @ApiOperation(value = "上传图片")
    @ApiImplicitParam(name = "file",value = "图片上传",required = true,dataTypeClass = MultipartFile.class,
            allowMultiple = true,paramType = "query")
    @PostMapping(value = "/upload")
    @ResponseBody
    public String insertOrderImg(@RequestParam("file") MultipartFile file) throws IOException {
    
    
        // 文件上传路径
        String location = "E:\\image\\";
        String originalFilename = file.getOriginalFilename();
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        //设置允许上传文件类型
        String suffixList = ".jpg,.png,.ico,.bmp,.jpeg";
        String imgUrl=null;
        // 判断是否包含
        if (suffixList.contains(extName.trim().toLowerCase())) {
    
    
            BufferedImage image = ImgUtil.read(file.getInputStream());
            int height = image.getHeight();
            int width = image.getWidth();
            // 保存文件的路径
            String path = location + originalFilename;
            // thumbnailator压缩存放路径
            String thumbPath= location+"thumbnailator"+originalFilename;
            //Img压缩存放路径
            String imgPath = location +"img"+ originalFilename;
            String newPath = location +"new"+ originalFilename;
            //同一文件SHA256进行哈希运算后值唯一
            String shaValue = DigestUtil.sha256Hex(file.getBytes());
            if (imgMap.containsKey(shaValue)) {
    
    
                log.info("重复的SHA{},已上传的文件名{}",shaValue,imgMap.get(shaValue));
                return "已经上传,不可重复";
            }
            imgMap.put(shaValue,originalFilename);
            //  spring的transferTo保存文件方法
            try {
    
    
                log.info("原图高{},宽{},大小{}KB",height,width,file.getSize()/1024);
                file.transferTo(new File(path));

                //Hutool图像编辑器压缩
                Img img = Img.from(file.getInputStream());
                Image img1 = img.scale(0.5f).setQuality(0.2f).getImg();
                byte[] bytes = ImgUtil.toBytes(img1, ImgUtil.IMAGE_TYPE_JPEG);
                log.info("Hutool压缩后高{},宽{},大小{}KB",img1.getHeight(null),img1.getWidth(null),bytes.length/1024);
                FileUtil.writeBytes(bytes,imgPath);

                //Thumbnails压缩 要读取压缩后图片大小和尺寸必须写后再读,没有Img编辑器压缩方便
                OutputStream outputStream1 = new FileOutputStream(thumbPath);
                Thumbnails.of(file.getInputStream())
                        .scale(0.5f)
                        .outputQuality(0.2f)
                        .toOutputStream(outputStream1);
                outputStream1.close();
                byte[] bytes1 = FileUtil.readBytes(thumbPath);
                BufferedImage read1 = ImgUtil.read(thumbPath);
                log.info("Thumbnails压缩高{},宽{},大小{}KB",read1.getHeight(),read1.getWidth(),bytes1.length/1024);

//                //Hutool另一种压缩方法,要读取压缩后图片大小和尺寸必须写后再读 ,没有Img编辑器压缩方便
//                OutputStream outputStream2 = new FileOutputStream(newPath);
//                ImageOutputStream imageOutputStream = ImgUtil.getImageOutputStream(outputStream2);
//                ImgUtil.scale(image, imageOutputStream, 0.5f);
//                ImgUtil.write(image,ImgUtil.IMAGE_TYPE_JPG,imageOutputStream,0.2F);
//                outputStream2.close();
//                byte[] bytes2 = FileUtil.readBytes(newPath);
//                BufferedImage read2 = ImgUtil.read(newPath);
//                log.info("Hutool直接压缩高{},宽{},大小{}KB",read2.getHeight(),read2.getWidth(),bytes2.length/1024);
                imgUrl = host + originalFilename;
            } catch (IOException e) {
    
    
                log.info("保存失败");
            }
        }
        return imgUrl;
    }

Continue to upload after the first upload is successful:
insert image description here
insert image description here
upload the same picture after changing its name:
insert image description here
upload the same picture after changing its format:
insert image description here

Upload another picture:
insert image description here

Guess you like

Origin blog.csdn.net/worilb/article/details/122973557