图片服务映射(SpringBoot mybatis-plus)

配置类

package cn.edu.qfnu.soft.common.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;


/**
 * 跨域配置
 * @author Louis
 * @date Jan 12, 2019
 */
@Configuration
public class CorsConfig  implements WebMvcConfigurer {
    /**
     * @author 吕嘉鸣
     * 配置图片服务映射
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    //将/img/映射D:/photos/ 比如访问http:127.0.0.1:8080/img/test.png 就代表访问项目部署服务器上面的D:/photos/test.png
        registry.addResourceHandler("/img/**").addResourceLocations("file:D:/photos/");

        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")	// 允许跨域访问的路径
                .allowedOrigins("*")	// 允许跨域访问的源
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")	// 允许请求方法
                .maxAge(168000)	// 预检间隔时间
                .allowedHeaders("*")  // 允许头部设置
                .allowCredentials(true);	// 是否发送cookie
    }
}

拼接映射访问路径

@Override
    public String 拼接映射访问路径( HttpServletRequest request) {

        ChkBillImg chkBillImg = chkBillImgMapper.selectOne(queryWrapper);

        String httpUrl = chkBillImg.getUrl().replace("D:\\photos\\", "").replace("\\", "/");
        try {
                //对ip和端口进行拼接
                httpUrl = "101.201.148.143"+":"+String.valueOf(request.getServerPort())+ File.separator +"img"+File.separator+httpUrl;
                httpUrl = "http://"+httpUrl.replace("\\", "/");
                //拼接后为http://101.201.148.143:8080/img/test.png 前端直接访问或者src里是这个url就可以映射出文件或者图片了
                chkBillImg.setUrl(httpUrl);
            } catch (SocketException e) {
                e.printStackTrace();
            }
        return httpUrl;
    }
posted @ 2021-05-08 16:15  Ideaway  阅读(86)  评论(1编辑  收藏  举报