You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue结合.NET后端:将接口返回图片设为img标签src的问题

解决Vue调用.NET接口显示图片的问题

你的代码里存在几个关键问题导致图片无法正常渲染,下面是针对性的修正方案:

1. 修正后端接口请求配置(api.js)

当前请求的Content-Type设置错误,且未指定正确的响应类型——图片属于二进制数据,axios默认会按JSON解析,直接导致数据损坏。修改GetPhotoByPath函数:

export const GetPhotoByPath = async (path) => {
  const token = getToken();

  if (token) {
    const config = {
      headers: {
        Authorization: `Bearer ${token}`,
        // 移除错误的multipart/form-data,GET请求无需该类型
      },
      responseType: 'blob', // 核心:指定响应为二进制Blob类型
    };

    try {
      const response = await api.get(
        `/v1/Photo/getByPath?filePath=${encodeURIComponent(path)}`, // 对路径编码,避免特殊字符报错
        config
      );

      if (response.status === 200) {
        return response;
      } else {
        console.error('Unexpected status code:', response.status);
        return false;
      }
    } catch (error) {
      console.error('Error retrieving image:', error.message);
      return false;
    }
  } else {
    clearStorage();
    console.error('Token not available. Redirecting to login...');
    return false;
  }
};

2. 修正Vue组件中的图片加载逻辑

模板中直接调用异步方法会触发重复执行,且async方法返回的是Promise,无法直接作为src值。建议将图片地址存在组件数据中:

方案一:使用Blob URL(推荐,性能更优)

<template>
  <img v-if="selectedImageSrc" :src="selectedImageSrc" alt="Oops! No image was found!" />
  <img v-else src="path/to/default/image.jpg" alt="Oops! No image was found!" />
</template>

<script>
import { GetPhotoByPath } from './api.js';

export default {
  data() {
    return {
      selectedItem: null,
      selectedImageSrc: ''
    };
  },
  watch: {
    // 监听selectedItem变化,自动加载对应图片
    selectedItem: {
      async handler(newVal) {
        if (newVal?.photoLocation) {
          this.selectedImageSrc = await this.getPhotoLocation(newVal.photoLocation);
        } else {
          this.selectedImageSrc = 'path/to/default/image.jpg';
        }
      },
      immediate: true // 初始化时自动执行一次
    }
  },
  methods: {
    async getPhotoLocation(photoLocation) {
      try {
        const response = await GetPhotoByPath(photoLocation);
        if (response && response.status === 200) {
          // 创建Blob URL,比base64更节省内存
          return URL.createObjectURL(response.data);
        } else {
          console.error('Failed to retrieve image:', response);
          return 'path/to/default/image.jpg';
        }
      } catch (error) {
        console.error('Error retrieving image:', error.message);
        return 'path/to/default/image.jpg';
      }
    }
  },
  beforeUnmount() {
    // 组件销毁时释放Blob URL,避免内存泄漏
    if (this.selectedImageSrc.startsWith('blob:')) {
      URL.revokeObjectURL(this.selectedImageSrc);
    }
  }
};
</script>

方案二:转Base64格式(适用于必须用base64的场景)

如果业务需求必须使用base64,修改getPhotoLocation方法:

async getPhotoLocation(photoLocation) {
  try {
    const response = await GetPhotoByPath(photoLocation);
    if (response && response.status === 200) {
      return new Promise((resolve) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result); // reader.result即为base64格式的dataURL
        reader.readAsDataURL(response.data);
      });
    } else {
      console.error('Failed to retrieve image:', response);
      return 'path/to/default/image.jpg';
    }
  } catch (error) {
    console.error('Error retrieving image:', error.message);
    return 'path/to/default/image.jpg';
  }
}

额外注意点

  • 后端接口需确保返回正确的Content-Type响应头(如image/jpeg、image/png等),否则Blob URL或base64可能无法正常解析。

内容的提问来源于stack exchange,提问作者Martin de Jong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 21:16:10