springboot图片上传,虚拟路径的配置

1.application.properties配置

#静态资源对外暴露的访问路径
file.staticAccessPath=/upload/**
#文件上传目录
file.uploadFolder=D:/upload/

2.配置文件实体化

 

package com.example.demo.upload;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Component
@Configuration  
<!--此注解可以
    @Configuration底层是含有@Component ,所以@Configuration 具有和 @Component 的作用。

    @Configuration可理解为用spring的时候xml里面的<beans>标签。

    @Configuration注解可以达到在Spring中使用xml配置文件的作用。

    @Bean可理解为用spring的时候xml里面的标签
-->
@ConfigurationProperties(prefix="file") 
<!--
    此注解可以映射配置文件中所有以'file'开头的文件,相对于 @Configuration ,更加的集中一             
-->
public class UploadFilePathConfig implements WebMvcConfigurer {

    @Value("${server.port}")
    private String port;
    @Value("${file.staticAccessPath}")
    private String staticAccessPath;
    @Value("${file.uploadFolder}")
    private String uploadFolder;

    /**
     * 重写这个方法即可配置虚拟路径
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder);
    }
    public String getPort() {
        return port;
    }
    public void setPort(String port) {
        this.port = port;
    }
    public String getStaticAccessPath() {
        return staticAccessPath;
    }
    public void setStaticAccessPath(String staticAccessPath) {
        this.staticAccessPath = staticAccessPath;
    }
    public String getUploadFolder() {
        return uploadFolder;
    }
    public void setUploadFolder(String uploadFolder) {
        this.uploadFolder = uploadFolder;
    }
}

3.调用   

    使用@autowired即可

 

此时访问的路径就是:http://localhost:8008/upload/图片名

 

注:

这是一种图片上传访问图片的方法,也可以使用nginx反向代理访问图片

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值