Server-side local image storage/reading solution

need

        Store the picture passed by the front end in a specified directory of the project, and store the relative path of the picture in the project to the database. After the front end obtains the relative path, it can directly access the picture.

Technical realization:

        In the SpringBoot project, we can create a "static" directory under the resource directory. In this directory, we can place static pages such as images/HTML, and they can be accessed directly on the browser. The example is as follows:

Then we access the IP: project port/project prefix/the resource path starting from the static directory to access the static resource.

Difficulty 1. Resource hot deployment fails:

        The current demand requires us to achieve a state similar to hot deployment, which means that after uploading and saving the image, the image can be accessed directly without restarting the project, recompiling and loading the image. However, I found some articles on the Internet to develop ideas. After hot deployment of the project, it still cannot achieve the expected results.

Difficulties solved:

        Since the company's project needs to be deployed on the server to interact with the front-end (deployed to the Pagoda), after the front-end uploads a picture, a subdirectory will be generated in the jar package directory of the Pagoda interface.

 I clicked on it and found that its directory structure was consistent with the project's directory structure, and the uploaded pictures were all consistent.

         After testing, I found that when I directly access the photo data in this directory through an external browser, I can directly obtain it. Then the problem is obvious.

Difficulty 2. How to obtain data other than the jar package?

        Because after I packaged the project into a jar package, according to the previous method, what I accessed was actually the compiled fixed code inside the jar package, but the newly introduced pictures I introduced were actually stored outside the location of the jar package. in a subdirectory, so it is definitely not what you expect.

Difficulties solved:

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**").addResourceLocations("file:pipayshop-api/src/main/resources/static/images/");
    }
}

        This code is a Spring Boot configuration class used to configure resource processors in web applications.

        In this code, WebConfigthe class implements WebMvcConfigurerthe interface and overrides addResourceHandlersthe methods. This method is used to configure the processor of static resources.

        In this example, addResourceHandlersthe method registers a resource handler to handle URL requests starting with "/images/". These requests will be mapped to the specified resource location.

        Specifically, addResourceHandler("/images/**")a URL pattern is specified, i.e. all requests starting with "/images/". addResourceLocations("file:pipayshop-api/src/main/resources/static/images/")The resource storage location is specified, that is, in the project directory pipayshop-api/src/main/resources/static/images/.

        After this configuration, when the application receives a URL request starting with "/images/", it will find and return the corresponding static resource file for client access.

        The function of this code is to map the static image resources in the specified directory in the project to the specified URL path, so that these images can be accessed through the URL.


final effect:

        I uploaded a picture on the front end. After processing on the back end, the picture is stored in a directory under static, and the relative path is stored in the database. When querying data, the relative path is returned directly, and the front end directly accesses the IP: project Port/Project prefix/The resource path starting from the static directory can access the static resource.


Tool sharing:

        For this set of image upload business implementation, a tool class has been packaged to simplify the operation of xdm, and you can directly operate CV!

   public static String uploadFile(MultipartFile multipartFile,String path) {
        if (multipartFile.isEmpty()) {
            throw new BusinessException("文件不能为空") ;
        }

        String fileName = multipartFile.getOriginalFilename();

        if ("".equals(fileName)) {
            return "文件名不能为空";
        }
        
        String postStr = fileName.substring(fileName.lastIndexOf("."));
        String preStr = StringUtil.generateShortId();
        fileName = preStr +  postStr;
        File readPath = new File(UPLOAD_PRE+PRE+path);
        if (!readPath.isDirectory()) {
            readPath.mkdirs();
        }
        //将文件复制到指定路径
        File destFile = new File(readPath.getAbsolutePath()+SEPARATOR + fileName);


        try {
            FileCopyUtils.copy(multipartFile.getBytes(), destFile);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return SEPARATOR+PRE+path+SEPARATOR+fileName;
    }

        Through this method, we only need to pass in the file object and its specific sub-package directory in the resources/static/images directory, and we can store the file object in the specified sub-package directory.

Instructions for use: 

Controller:

@PostMapping("itemTopImags")
    @ApiOperation("网店头像图片上传")
    public ResponseVO<String> itemTopImagsUp(MultipartFile multipartFile){
        try {
            String itemTopImags = FileUploadUtil.uploadFile(multipartFile, FileUploadUtil.ROOM_TOP_IMG);
            return ResponseVO.getSuccessResponseVo(itemTopImags);
        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessException("网店头像图片上传失败,请联系后台人员");
        }
    }
public static final String ROOM_TOP_IMG="room_top_img";

After this interface receives a picture, the final picture will be stored in the following location 

Guess you like

Origin blog.csdn.net/weixin_73077810/article/details/132214201