Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/473.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将JSON结果设置为';src&x27;属于';img&x27;要在ASP.NET MVC4中显示图像?_Javascript_Jquery_Ajax_Json_Asp.net Mvc 4 - Fatal编程技术网

Javascript 如何将JSON结果设置为';src&x27;属于';img&x27;要在ASP.NET MVC4中显示图像?

Javascript 如何将JSON结果设置为';src&x27;属于';img&x27;要在ASP.NET MVC4中显示图像?,javascript,jquery,ajax,json,asp.net-mvc-4,Javascript,Jquery,Ajax,Json,Asp.net Mvc 4,在我的视图中,我已经获得了AJAX提供的JSON格式的图像的绝对路径。它看起来像: var addresIMG=data.result.sourcefile;//address is 'D:/jqueryfileuploadmvc4/MVC4Appl/App_Data/1.png' 但是,视图无法渲染图像,因为属性“src”图像应如下所示: <img src="@Url.Content("~/App_Data /" + "1.png")" /> 但我的观点是: //它不正

在我的视图中,我已经获得了AJAX提供的JSON格式的图像的绝对路径。它看起来像:

var addresIMG=data.result.sourcefile;//address is 'D:/jqueryfileuploadmvc4/MVC4Appl/App_Data/1.png'
但是,视图无法渲染图像,因为属性“src”图像应如下所示:

<img src="@Url.Content("~/App_Data /" + "1.png")"  /> 

但我的观点是: //它不正确,因为映像的地址应该指向服务器

JS:


$(文档).ready(函数(){
$('#fileupload')。fileupload({
数据类型:“json”,
url:“/Home/UploadFiles”,
自动上传:对,
完成:函数(e,数据){
var addresIMG=data.result.sourcefile;//地址为'D:/jqueryfileuploadmvc4/MVC4Appl/App_data/1.png''
$(“.file_source”).attr('src',data.result.sourcefile);//它设置了一个绝对路径,但它不正确。图像ID地址应该类似于src=“@Url.Content”(~/App_data/“+”1.png”)”
}
}).on('fileuploadprogressall',函数(e,数据){
var progress=parseInt(data.loaded/data.total*100,10);
$('.progress.progress bar').css('width',progress+'%');
});
});

是否可以根据JSON的结果分配“src”属性?

JSON数据应该包括相对或绝对URL,而不是文件系统路径。浏览器不能直接访问服务器的文件系统,因此src属性必须使用URL

服务器必须通过映射文件系统路径生成正确的URL,如下所示:

var imageUrl = Url.Content("~/App_Data/1.png");
填充模型的服务器端逻辑必须设置sourcefile属性,然后将其序列化并作为JSON发送到客户端。比如说

var model = GetModelFromDatabase();  //any code that sets your model object
model.sourcefile = imageUrl;

然后可以使用
var addresIMG=data.result.sourcefile没有问题

所以我的JSON响应应该包含:“Server.MapPath(“~/App_Data/1.png”)”?我猜我的浏览器无法识别这样的源地址,因为点击按钮后,这个JSON响应将在浏览器中分配。但我会试试。我已经用一个例子更新了我的答案。我假设您正在MVC控制器操作中填充模型,因此您应该能够使用Url.Content从路径获取Url。Server.MapPath显然与此相反,因此对您的情况没有任何帮助。我是否正确理解model.sourcefile的地址类似于“'D:/jqueryfileuploadmvc4/MVC4Appl/App_Data/1.png”?不,不应该是这样,因为路径对浏览器没有任何意义。浏览器希望src属性具有一个URL值
var model = GetModelFromDatabase();  //any code that sets your model object
model.sourcefile = imageUrl;