使用文件设置 img src

Set img src with file

提问人:Martin de Jong 提问时间:11/4/2023 最后编辑:BarmarMartin de Jong 更新时间:11/4/2023 访问量:58

问:

我有一个带有 .NET 后端的 Vue 应用程序。在我的应用程序中,我有可以上传的项目。当我上传图像时,文件将保存在我的后端,并将文件位置发送到数据库。当我单击页面上的某个项目时,我使用文件路径向服务器发出 get 请求,端点返回图像。我希望这个图像数据集作为我的 <img> 的 src。

我尝试使用结果数据以及 base64 编码图像设置 src。

我有这个方法:

async getPhotoLocation(photoLocation) {
  try {
    const response = await GetPhotoByPath(photoLocation);
    if (response && response.status === 200) {
      return `data:${response.headers["content-type"]};base64,${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";
  }
},

这个方法在我的图像的 src 中是这样调用的:

<img v-if="selectedItem" :src="getPhotoLocation(selectedItem.photoLocation)" alt="Oops! No image was found!" />

这是我的 api.js 文件中的函数:

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

  if (token) {
    const config = {
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "multipart/form-data",
      },
    };

    try {
      const response = await api.get(
        "/v1/Photo/getByPath?filePath=" + path,
        config
      );

      if (response.status === 200) {
        return response;
      } else {
        console.error("Unexpected status code:", response.status);
        return false;
      }
    } catch (error) {
      console.error("Error uploading image:", error.message);
      return false;
    }
  } else {
    clearStorage();
    console.error("Token not available. Redirecting to login...");
    return false;
  }
};
JavaScript 图像 vue.js 文件

评论

0赞 Lucas 11/4/2023
你为什么不简单地使用图像的URL?我真的不明白你在这里想做什么selectedItem.photoLocation
0赞 Martin de Jong 11/4/2023
@Lucas 我想显示图片的地方在前端网站和后端,存储图像的地方在另一台服务器上,因此图像位置不存在于页面上。
0赞 Lucas 11/4/2023
好的,我明白了。但是,如果你的后端服务提供图像作为响应,你应该能够直接在你的img src中使用这个后端服务URL,假设你返回了正确的Content-Type标头和响应(这取决于图像类型)
0赞 Martin de Jong 11/5/2023
@Lucas 我不起作用......

答: 暂无答案