【问题标题】:Serve up images from network to View in ASP.NET MVC从网络提供图像以在 ASP.NET MVC 中查看
【发布时间】:2013-11-15 03:14:43
【问题描述】:

我正在尝试从我的服务器加载图像,然后将它们加载到视图中:

var files = _directoryInfo.GetFiles()
            .Where(x => x.Name.Contains(request.WarrantyReference))
            .ToList();

model.Photos = files;

return View(model);

然后在视图中我正在做:

@if (Model.Photos.Count > 0)
{
    @Html.Partial("_Photos", Model.Photos)
}

_照片:

@model List<FileInfo>
<div class="ui items">
    @foreach (var photo in Model)
    {
        <div class="item">
            <div class="image">
                <img src="@photo.FullName">
            </div>
        </div>
    }
</div>

但是什么也没有出现,我在控制台中收到以下错误:

Not allowed to load local resource: 
    file://my-server/dataphoto/WX0001 1.jpg 

所以我想知道是否可以将照片临时存储在我的服务器上以将它们提供给视图,或者是否有其他方法可以解决这个问题?

【问题讨论】:

    标签: asp.net-mvc-4


    【解决方案1】:

    将文件名(或某些标识符)存储在您的模型中。

    型号

    class Model
    {
        IList<string> Photos { get; set; }
    

    创建一个 HtmlHelper 来显示您的照片图像。

    在您的示例中,您可以将“WX0001 1.jpg”存储为照片标识符,然后当您从网络服务器读取文件时,您会在特定目录中查找。

    查看

    @model List<FileInfo>
    <div class="ui items">
        @foreach (var photo in Model)
        {
            <div class="item">
                <div class="image">
                    @Html.PhotoImage(photo)
                </div>
            </div>
        }
    </div>
    
    public static MvcHtmlString PhotoImage(this HtmlHelper html, string id)
    {
        var img = new TagBuilder("img");
    
        var your_image_byte_array = read_image_from_server_using_id;
        var base64 = Convert.ToBase64String(your_image_byte_array);
    
        img.Attributes.Add("src", String.Format("data:image/gif;base64,{0}", base64));
    
        return MvcHtmlString.Create(img.ToString());
    }
    

    或者,看看使用 Action 方法来显示图像...Convert Byte Array to Image and Display in Razor View

    【讨论】:

      【解决方案2】:

      您需要将文件复制到用于服务/托管网站的 AppPool 的 ASP.NET 用户可以访问的位置。或者,授予共享应用程序池帐户读取权限。另一种方法是读取文件并将它们存储在 byte[] 中,最后在屏幕/视图上呈现它,而无需实际将文件写入磁盘。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-05
        • 2016-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多