提问人:Martin de Jong 提问时间:11/4/2023 最后编辑:BarmarMartin de Jong 更新时间:11/4/2023 访问量:58
使用文件设置 img src
Set img src with file
问:
我有一个带有 .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;
}
};
答: 暂无答案
评论
selectedItem.photoLocation