How to display local images in the front-end Vue page

<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();
//数据打印出来如下图所示

We use the <img> tag to display images, and the src attribute is set to the image request path.

"http://localhost:8888/image/img.jpg" format, that is, this request will be sent to the backend to obtain the image.

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

But the picture is stored in a local file, so how can it be found?

This requires mapping the path of this request to find the real address where the image is stored.

我们需要写一个配置类,添加如下的方法
@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系统,则不加盘符
*/
    }
}

Guess you like

Origin blog.csdn.net/xuan__xia/article/details/134088836