Not allowed to load local resource: 报错解决方法

出现这样的错一般为直接引用项目外的资源(图片,视频).

image

然后打开网页结果

image

不允许直接访问我们就需要配置一个虚拟路径来访问系统中的资源.

容器为tomcat解决方法

1. 打开tomcat服务界面 在下面选择Modules 然后选择Add Web Module

image

2. 选择Browse 选择你的资源目录,然后填写path 假如选择的为d盘 d盘下有一张a.png 那么你再写<img src="/image/a.png">即可

image

使用的spring boot

因为是内置的tomcat所有没法想上面一样直接选择.

我们可以写一个配置类

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 

@Configuration
public class MyWebConfig implements WebMvcConfigurer {    
@Override   
public void addResourceHandlers(ResourceHandlerRegistry registry) {  
     registry.addResourceHandler("/image/**").addResourceLocations("file:E:/uploadTool/result/");    
}
}

路径ResourceHandler (/image/**)跟上面tomcat/image为一个道理, ResourceLocations("....")为你选择的系统资源目录

需要在目录前加file:

然后同tomcat直接使用<img src="/image/a.png">

base64转码

除此之外,应该还有一个方法:
即img标签可显示base64转码的图片。将本地图片先进行base64转码,之后再img标签中显示,这样问题解决了。
1、后台提供转码

public String getBaseImg(String imgPath) throws CustomException {
 
    InputStream in = null;
    byte[] data = null;
    try {
        in = new FileInputStream(WorkConstant.PROIMAGE_DIR_REALNAME + "/webSystem/" + imgPath);
        data = new byte[in.available()];
        in.read(data);
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //进行Base64编码
    BASE64Encoder encoder = new BASE64Encoder();
    return encoder.encode(data);
}

2、前台img标签显示图片

 $.ajax({
                url:'./getBaseImg.do',
                data:{imgPath:$("#webImage").val()},
                success:function (data) {
                    $("#webImageTrue").attr("src", "data:image/jpeg;base64,"+data);
                }
            })

这种就可以实现img标签显示本地文件了

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。