【发布时间】:2020-01-09 21:35:29
【问题描述】:
我有一张需要通过 jquery 或 javascript 动态设置的图片
<img id="myImage" src="" />
我的视图名为“UserProfile”,我的控制器名称为“User”,生成的 url 为:https://localhost/Carpool.Web/User/UserProfile
我的图片位于 wwwroot/images 文件夹下
现在当我使用以下任何一种时,我得到 404 并且图像不显示:
$("#myImage").attr({ "src": "/wwwroot/images/info.png" }); //console => <img id="myImage" src="https://localhost/Carpool.Web/User/UserProfile/wwwroot/images/info.png">
$("#myImage").attr({ "src": "~/images/info.png" });//console => <img id="myImage" src="~/images/info.png">
$("#myImage").attr({ "src": "/images/info.png" });//console => <img id="myImage" src="https://localhost/Carpool.Web/User/UserProfile/images/info.png">
$("#myImage").attr({ "src": "images/info.png" }); //console => <img id="myImage" src="https://localhost/images/info.png">
document.getElementById("myImage").src // tried all as above
如果我的视图是“索引”,那么我没有这个问题,网站徽标也可以正常显示 这与我升级到 asp.net core 3.1 有关吗?
【问题讨论】:
-
听起来你的图像有绝对路径。这就是为什么如果这些页面与索引不在同一级别,它将在索引而不是其他页面上工作。然后,您必须先导航到正确的文件夹才能获取图像。
-
有没有办法解决这个问题?我不想硬编码完整路径,因为我们有不同的环境
-
my images located under wwwroot/images folder你确定用https://localhost/images/<image_file_name>确实无法访问图片吗?请分享您的项目文件夹结构,以便我们更好地解决问题。
标签: javascript jquery asp.net-core