Scenes
After the file is uploaded to the server, you need to access the corresponding file on the server through the URL, which can be a picture or other files.
accomplish
Since SpringBoot is essentially an embedded tomcat, it is not possible to directly access the required resources from the tomcat directory, so you need to inherit WebMvcConfigurer to implement your own interceptor, and map the local folder address for access. Pay attention to the /show/**
path
here Be sure to add "/" at the end of , which is the file separator, otherwise it will not be correctly mapped to the corresponding folder. That is, the
difference file:D:/Demo/
between and file:D:/Demo
, you must use the former to access correctly
package com.hwh.communitymanage.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.io.File;
/**
* @description:
* @author: HwH
* @create: 2022-11-24 23:11
**/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
// 静态资源展示
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// PS:注意文件路径最后的斜杠(文件分隔符),如果缺少了,就不能够正确的映射到相应的目录
String basePath = "file:D:/Demo/";
registry.addResourceHandler("/show/**").addResourceLocations(basePath);
}
}
test
After completing the above configuration, start the project, and access the URL address of the file in the directory
: localhost:8080/show/1.jpg
if the picture is displayed, it means that it can be accessed correctly
If authorization verification such as Shiro is added, it needs to be added to the corresponding whitelist, or the Token should be carried when accessing, so that Shiro can pass the verification