在ASP.NET razor视图中显示字节数组图像。 [英] Displaying byte array image in ASP.NET razor view.

查看:77
本文介绍了在ASP.NET razor视图中显示字节数组图像。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在asp.net razor视图中在sql server数据库中显示我的图像。我已经做了保存动作控制器。请有人帮助我。我没有创建任何控制器动作来渲染图像



我尝试过:



以下是我的控制器保存图像字节操作







public ActionResult Create()

{

ViewBag.Owner_ID = new SelectList(db.Owners,OwnerID,UserName);

返回查看();

}



// POST:/ Facility / Create

//为了防止过度攻击,请启用您要绑定的特定属性,对于

//更多详细信息,请参阅http://go.microsoft.com/fwlink/?LinkId=317598.

[HttpPost]

[ValidateAntiForgeryToken]



public ActionResult Create(Facility model,HttpPostedFileBase image1)

{

var db = new eReservatorEntities7();



if(image1!= null)

{

model.Image = new byte [image1.ContentLength];

image1.InputStream.Read( model.Image,0,image1.ContentLength);



}



db.Facilities.Add(模型);

db.SaveChanges();

返回查看(模型);

}





}

i want to know how can i display my image in sql server database in asp.net razor view. i already did the saving action controllers. please anyone help me. i didnt create any controller action to render the image

What I have tried:

following is my controller action for save image byte



public ActionResult Create()
{
ViewBag.Owner_ID = new SelectList(db.Owners, "OwnerID", "UserName");
return View();
}

// POST: /Facility/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]

public ActionResult Create(Facility model, HttpPostedFileBase image1 )
{
var db = new eReservatorEntities7();

if (image1 != null)
{
model.Image = new byte[image1.ContentLength];
image1.InputStream.Read(model.Image, 0, image1.ContentLength);

}

db.Facilities.Add(model);
db.SaveChanges();
return View(model);
}


}

public ActionResult Create()
        {
            ViewBag.Owner_ID = new SelectList(db.Owners, "OwnerID", "UserName");
            return View();
        }

        // POST: /Facility/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        
        public ActionResult Create(Facility model, HttpPostedFileBase image1 )
        {
            var db = new eReservatorEntities7();

            if (image1 != null)
            {
                model.Image = new byte[image1.ContentLength];
                image1.InputStream.Read(model.Image, 0, image1.ContentLength);

            }
            
                db.Facilities.Add(model);
                db.SaveChanges();
                return View(model);
            }

            
        }

推荐答案

Razor视图代码只生成HTML。就是这样,仅此而已。图像不是HTML,因此Razor代码无法生成图像的HTML。它可以生成HTML IMG标签来获取图像。



那么,HTML页面如何获得图像?它必须向服务器发出第二个请求,无论是对服务器上的文件的直接请求,还是对使用您提供给Razor代码的生成HTML IMG标记的标识符编写的控制器的请求。服务器将返回标记中指定的文件,或者必须执行任何操作以获取图像数据并以字节流的形式将其返回给客户端。
Razor view code just generates HTML. That's it, nothing more. Images are not HTML so the Razor code cannot generate the HTML for an image. It can generate the HTML IMG tag to get the image though.

So, how does an HTML page get an image? It has to make a second request to the server, be it a direct request for a file on the server or a request to a controller you write using some identifier you provided to the Razor code to generate the HTML IMG tag. The server will either return the file specified in the tag or has to do whatever to get the image data and return it to the client in a stream of bytes.


您需要一个返回的操作该文件并将img标记的src设置为该操作。对于我的数据库我有



ID,文件名,MIME,ImageData



所以我读了一个列表这些在我的索引方法中



You need an action that returns the file and you set the src of an img tag to be that action. For my database I have

ID, Filename, MIME, ImageData

so I read a list of these in my index method

public class GalleryModel
{
    public int ID { get; set; }
    public string Filename { get; set; }
}







public ActionResult Index()
{
    List<GalleryModel> model = new List<GalleryModel>();

    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString))
    {
        SqlCommand com = new SqlCommand();
        com.Connection = con;
        com.CommandText = "select ID, Filename from Gallery";
        con.Open();
        SqlDataReader r = com.ExecuteReader();
        while (r.Read())
        {
            model.Add(new GalleryModel { ID = (int)r["ID"], Filename = (string)r["Filename"] });
        }
    }

    return View(model);
}





视图就好像





The view is like

@model List<GalleryModel>

<table>
@foreach (var gallery in Model)
{
    <tr>
        <td>
            @gallery.Filename
        </td>
        <td>
            <img src="@Url.Action("GetImage", "Gallery", new {id = gallery.ID})" />
        </td>
    </tr>
}
</table>





现在我们需要在Gallery控制器上实现GetImage操作< br $>




Now we need to implement the GetImage action on the Gallery controller

[HttpGet]
public ActionResult GetImage(int id)
{
    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString))
    {
        SqlCommand com = new SqlCommand();
        com.Connection = con;
        com.CommandText = "select Filename, MIME, ImageData from Gallery where ID = @id";
        com.Parameters.AddWithValue("@id", id);
        con.Open();
        SqlDataReader r = com.ExecuteReader();
        if (r.Read())
        {
            return File((byte[])r["ImageData"], (string)r["MIME"], (string)r["Filename"]);
        }
    }

    return new EmptyResult();
}





我正在使用ado.net,但您可以插入您的Entity Framework代码,一般主要是同样。



I'm using ado.net, but you can plug in your Entity Framework code, the general principal is the same.


这篇关于在ASP.NET razor视图中显示字节数组图像。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆