The Springboot backend obtains native image resources through path mapping

Project scenario:

The processing and viewing of pictures in the project is essential. This article will explain how to obtain the picture resources of the local computer through the project path


As shown in the figure, there are some pictures under the picture test folder (the folder name should not contain Chinese ) on the D drive of my local computer .

 We want to access these pictures on the browser, it is very simple, we only need to fill in our relevant path in the browser navigation bar

For example, my path is: D/file test/4c0df32a590bdc5c37eb6b145d4475f1.png

 But how do we access these images through request responses in our project? These pictures are the resources on the local computer, this is when we can think of our WebMvc static resource parser ResourceHandlers

Code

Create a new spring component container, implement WebMvcConfigurer, rewrite the method of adding a resource processor, and add a picture resource processor

package com.lyj.config;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Component
public class MyWebMvcConfig implements WebMvcConfigurer {

    private String filePath = "D:文件测试";
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/view/**").addResourceLocations("file:"+filePath+"/");
    }
}

At this time, we only need to write the relevant mapping path. The project port I opened is 8036

Since we have configured the resource processor, localhost:8036/view/4c0df32a590bdc5c37eb6b145d4475f1.png will be intercepted and processed into   file:D: file test/4c0df32a590bdc5c37eb6b145d4475f1.png

Combined with image submission, when the image is submitted, the file path is saved as the corresponding project path, and the image can be displayed on the project page through the project path mapping. In the next article, I will explain how springboot handles image upload and image submission. Path storage problem

Guess you like

Origin blog.csdn.net/liyingjie2001/article/details/124914566