What others can do, you can do ⏱

preface

When we use SprinBboot to upload the file, we will upload the file to the hard disk specified path, at this time we want to access the file in the client, there will be 404 cannot access the situation, next to share with you developers how to configure virtual path to solve the problem of file cannot access.

Implementation approach

  • A new configuration class inherits from WebMvcConfigurerAdapter
  • Add the real path and virtual path of the uploaded file on the hard disk to the YML file
  • Override the addResourceHandlers method to configure the virtual path

The implementation process

  • Add the virtualPathConfigAdapter class to the config package and override the addResourceHandlers method
package com.lk.config;

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

import java.io.File;

@Configuration
public class virtualPathConfigAdapter extends WebMvcConfigurerAdapter {
    // The path to the file on the hard disk
    @Value("${uploadFilePath}")
    private String uploadFilePath;
    // Virtual access path
    @Value("${virtualUploadPath}")
    private String virtualUploadPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /* * The virtual path configured here takes effect for both internal tomcat and external Tomcat. If external Tomcat is used, you do not need to configure it in the configuration file */
        registry.addResourceHandler(virtualUploadPath +"/ * *").addResourceLocations("file:"+ uploadFilePath + File.separator);
        // Aliccloud (mapping path to remove drive letter)
        //registry.addResourceHandler("/ueditor/image/**").addResourceLocations("/upload/image/");
        super.addResourceHandlers(registry); }}Copy the code
  • Add configuration in application.yml
# file storage path | virtual real upload path
uploadFilePath: "/Volumes/DataStorage/fileStorage/uploads"
virtualUploadPath: "/uploads"
Copy the code

Implementation effect

The real path file on the hard disk

The browser accesses the url

Write in the last

  • If there are any errors in this article, please correct them in the comments section. If this article helped you, please like it and follow 😊
  • This article was first published in the Nuggets. If you need to reprint it, please leave a comment at 💌