前端Vue页面中如何展示本地图片

<el-table :data="tableData" stripe style="width: 100%">
      <el-table-column prop="imgUrl" label="图片">
        <template v-slot="scope">
          <img :src= "http://localhost:8888/image/ ' + scope.row.imgUrl" />
        </template>
      </el-table-column>
</el-table>

//tableData是从数据库查询得到的数据
//scopre.row.imgUrl是图片的url地址,在这个项目中为图片在数据库中存储的名字

//这个是向后端获取数据的请求,得到数据之后将数据赋值给tableData
const initProductList=async()=>{
  const res = await axios.post("image/list",queryForm.value)
  tableData.value = res.data.orderList;
  console.log("tableData is",tableData)
  total.value = res.data.total;
}
initProductList();
//数据打印出来如下图所示

我们使用<img>标签展示图片,src属性设置成图片请求路径

"http://localhost:8888/image/img.jpg"的格式,也就是会向后端发送这个请求获取图片。

 <img :src= "http://localhost:8888/image/ ' + scope.row.imgUrl" />

但是图片是存放在本地的某个文件里,那如何才能找到呢?

这就需要对这个请求的路径进行映射,以找到真正的存放图片的地址。

我们需要写一个配置类,添加如下的方法
@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {            
    registry.addResourceHandler("/image/**").addResourceLocations("file:D:\\img\\");

/*
    在这段代码中,addResourceHandlers方法用于添加资源处理器。ResourceHandlerRegistry对象用于注册资源处理器,并指定资源的访问路径和存放位置。
        /image/**对应的资源就放在D盘的img目录下,通过这样的配置当前端发送
http://localhost:8888/image/123.jpg时,应用程序会将请求映射到本机 D:\img\123.jpg路径下的文件,并将文件返回给前端。
如果是Linux系统,则不加盘符
*/
    }
}

猜你喜欢

转载自blog.csdn.net/xuan__xia/article/details/134088836