今天在上传图片之后发现访问图片报404。最终配置了虚拟路径。在此总结一下。
项目的上传路径是static/upload/articleUpload下。发现上传成功,然后访问路径是
http://localhost:8080/community/upload/articleUpload/a926f98a36724d928d4b1fde8425d417_loginimg.jpg
其中community是配置的项目根路径,upload放在了static目录下。但是访问404,只有项目重新启动才能访问。
原因:是服务器的保护措施导致的,服务器不能对外部暴露真实的资源路径,需要配置虚拟路径映射访问。
那么我们现在解决的就是:当我们访问https:localhost:8080/community/upload/articleUpload/xx.png
实际上是去访问D:/Program Files/Java/Java IDEA/springboot/project/community/src/main/resources/static/upload/
那么就需要通过配置虚拟路径来解决此问题。
首先在application.properties中配置
然后新建一个配置类,标注注解
package com.nowcoder.community.config;
import com.nowcoder.community.controller.interceptor.AlphaInterceptor;
import com.nowcoder.community.controller.interceptor.LoginRequiredInterceptor;
import com.nowcoder.community.controller.interceptor.LoginTicketInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/*
配置类:
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Value("${upload}")
private String uploadPattern;
@Value("${upload.location}")
private String uploadLocation;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(uploadPattern).addResourceLocations("file:"+uploadLocation);
}
}
主要遇到的的另一个问题时配置了还是报404,原因是配置的upload.location在最后没有加/因此报404.
扫描二维码关注公众号,回复:
12883473 查看本文章
然后自己的图片是以upload/...
存放到数据库中,最后前端获取终于成功了。