如何将JSON结果设置为'src'共'img'以在ASP.NET MVC4中显示图像

How to set JSON result to 'src' of 'img' to show an image in ASP.NET MVC4?

本文关键字:ASP 以在 NET MVC4 图像 显示图 显示 img src JSON 结果      更新时间:2023-09-26

在我的视图中,通过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:

<script type="text/javascript">
$(document).ready(function () {
    $('#fileupload').fileupload({
        dataType: 'json',
        url: '/Home/UploadFiles',
        autoUpload: true,
        done: function (e, data) {  
             var addresIMG=data.result.sourcefile;//address is 'D:/jqueryfileuploadmvc4/MVC4Appl/App_Data/1.png''
            $(".file_source").attr('src', data.result.sourcefile);//it sets an absolute path and it is incorrect. The image iddress should look like src="@Url.Content("~/App_Data /" + "1.png")" 

        }
    }).on('fileuploadprogressall', function (e, data) {
        var progress = parseInt(data.loaded / data.total * 100, 10);
        $('.progress .progress-bar').css('width', progress + '%');
    });
});
</script>

是否可以通过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;而不会出现问题