简体   繁体   English

从DataBase保存并显示图像

[英]Save and Display Image from DataBase

Not sure if this is close or not. 不确定这是否接近。 I'm creating an image field within the database table Events using the code 我正在使用代码在数据库表Events中创建一个图像字段

public string EvtImage { get; set; }

For a start I'm not even sure if it should be a string. 首先,我甚至不确定它是否应该是一个字符串。 I am then trying to add the Image to the database by using the code 然后我尝试使用代码将Image添加到数据库中

SqlCommand cmd = new SqlCommand("insert into Events (AspNetUsersId,EvtName,EvtType,EvtDescription,EvtDate,EvtVote, EvtImage) values (@AspNetUsersId, @EvtName, @EvtType, @EvtDescription, @EvtDate, @EvtVote, @EvtImage)");

cmd.Parameters.AddWithValue("@AspNetUsersId", userId);
cmd.Parameters.AddWithValue("@EvtName", eventName.Text);
cmd.Parameters.AddWithValue("@EvtType", eventType.Text);
cmd.Parameters.AddWithValue("@EvtDescription", eventDescription.Text);
cmd.Parameters.AddWithValue("@EvtDate", datetimepicker.Value);
cmd.Parameters.AddWithValue("@EvtVote", 0);

if (eventImage.HasFile)
{
    var  imagename = eventImage.FileName;
    cmd.Parameters.AddWithValue("@EvtImage", imagename);
}

loadDatabase(cmd);

And once this is added I'm trying to display it within a Repeater in ASP.NET using the code 一旦添加了这些,我就会尝试使用代码在ASP.NET中的Repeater中显示它

<asp:Repeater runat="server" ID="repeaterEvent">
    <ItemTemplate>
        <div class="jumbotron">

            <h2><asp:Label ID="lblEventTest" runat="server" Text='<%#Bind("EvtName") %>'></asp:Label></h2>
            <h3><asp:Label ID="Label1" runat="server" Text='<%#Bind("EvtType") %>'></asp:Label></h3>
            <h4><asp:Label ID="Label3" runat="server" Text='<%#Bind("EvtDate") %>'></asp:Label></h4>
            <h4><asp:Label ID="Label2" runat="server" Text='<%#Bind("EvtDescription") %>'></asp:Label></h4>   
            <h4><asp:Label runat="server">Amount Attending: </asp:Label>
                <asp:Image ID="label6" runat="server" ImageUrl='<%#Bind("EvtImage") %>' />
            <asp:Label ID="Label4" runat="server" Text='<%#Bind("EvtVote") %>'></asp:Label></h4>
            <asp:Button runat="server" ID="eventButtonTest" Text="Attending" class="btn btn-primary" OnClick="EventVote_Click"/>
        </div>
    </ItemTemplate>
</asp:Repeater>

I am creating the Repeater by using the code: 我正在使用代码创建Repeater

SqlConnection conn = new SqlConnection(@"Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-StudentMoneySaver-20160203040444.mdf;Initial Catalog=aspnet-StudentMoneySaver-20160203040444;Integrated Security=True");

string query;
SqlCommand SqlCommand;
SqlDataReader reader;

SqlDataAdapter adapter = new SqlDataAdapter();
//Open the connection to db
conn.Open();

//Generating the query to fetch the contact details
query = "SELECT EvtName, EvtType, EvtDescription, EvtDate, EvtVote, EvtImage FROM Events";
SqlCommand = new SqlCommand(query, conn);
adapter.SelectCommand = new SqlCommand(query, conn);
//execute the query
reader = SqlCommand.ExecuteReader();
//Assign the results 
repeaterEvent.DataSource = reader;
//Bind the data
repeaterEvent.DataBind();

Follow below steps, 按照以下步骤,

In Database, you should have, 在数据库中,你应该有,

EvtImage image (datatype)

Declare as, 声明为,

public Byte[] EvtImage { get; set; }

Change while save, 保存时更改,

if (eventImage.HasFile && eventImage.PostedFile != null)
{
    //To create a PostedFile
    HttpPostedFile f = eventImage.PostedFile;
    //Create byte Array with file len
    EvtImage = new Byte[f.ContentLength];
    //force the control to load data in array
    f.InputStream.Read(EvtImage, 0, f.ContentLength);

    cmd.Parameters.AddWithValue("@EvtImage", EvtImage);
}

To display image, create handler as below, (change your table/columns as required) 要显示图像,请按如下所示创建处理程序(根据需要更改表/列)

<%@ WebHandler Language="C#" Class="ShowImage" %>

using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public class ShowImage : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
       Int32 empno;
       if (context.Request.QueryString["id"] != null)
            empno = Convert.ToInt32(context.Request.QueryString["id"]);
       else
            throw new ArgumentException("No parameter specified");

       context.Response.ContentType = "image/jpeg";
       Stream strm = ShowEmpImage(empno);
       byte[] buffer = new byte[4096];
       int byteSeq = strm.Read(buffer, 0, 4096);

       while (byteSeq > 0)
       {
           context.Response.OutputStream.Write(buffer, 0, byteSeq);
           byteSeq = strm.Read(buffer, 0, 4096);
       }       
       //context.Response.BinaryWrite(buffer);
    }

    public Stream ShowEmpImage(int empno)
    {
 string conn = ConfigurationManager.ConnectionStrings     ["EmployeeConnString"].ConnectionString;
        SqlConnection connection = new SqlConnection(conn);
        string sql = "SELECT empimg FROM EmpDetails WHERE empid = @ID";
        SqlCommand cmd = new SqlCommand(sql,connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", empno);
        connection.Open();
        object img = cmd.ExecuteScalar();
        try
        {
            return new MemoryStream((byte[])img);
        }
        catch
        {
            return null;
        }
        finally
        {
            connection.Close();
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }


}

Finally add asp image in aspx and add image url as, 最后在aspx中添加asp图像并添加图片网址,

Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;

Let me know if you have any difficulties. 如果您有任何困难,请告诉我。

In the code behind write a method called Collection() to retrieve images and other fields as a List of Events like below (Also it is better to use Using statements): 在后面的代码中编写一个名为Collection()的方法来检索图像和其他字段作为下面的事件列表(也最好使用Using语句):

public IEnumerable<Events> Collection()
{
    string address = "YourConnectionString";
    using (SqlConnection con = new SqlConnection(address))
    {
        con.Open();
        string qry = "select * from Events";
        SqlCommand cmd = new SqlCommand(qry, con);
        using (SqlDataReader dr = cmd.ExecuteReader())
        {
            if (!dr.HasRows) yield break;
            while (dr.Read())
            {
                Events evt = new Events
                {
                    Id = int.Parse(dr["Id"].ToString()),
                    EvtName = dr["EvtName"].ToString(),
                    EvtType = dr["EvtType"].ToString(),
                    EvtImage = dr["EvtImage"].ToString()
                };
                yield return (evt);
            }
        }
    }
}

And also a class: 还有一个课程:

public class Events
{
    public int Id { get; set; }
    public string EvtName { get; set; }
    public string EvtType { get; set; }
    public string EvtImage { get; set; }
}

Then to show this images you have two choice. 然后,要显示此图像,您有两个选择。 You can either use asp:Repeater with an asp:ObjectDataSource like this: 您可以将asp:Repeaterasp:ObjectDataSource如下所示:

<asp:Repeater ID="repeaterEvent" runat="server" DataSourceID="imgCats">
  <ItemTemplate>
     <div>
        <asp:Label ID="lblEventTest" runat="server" Text='<%#Bind("EvtName") %>'></asp:Label>
        <asp:Label ID="Label1" runat="server" Text='<%#Bind("EvtType") %>'></asp:Label>
        <img src='<%# Eval("EvtImage") %>' alt="" width="50"/>
     </div>                  
  </ItemTemplate>
</asp:Repeater>
<asp:ObjectDataSource ID="imgCats" runat="server" SelectMethod="Collection" 
      TypeName="WebApplication1.WebForm8">
</asp:ObjectDataSource>

Just don't forget to change the WebApplication1 in the TypeName to the name of your project and WebForm8 to the name of your page. 只是不要忘记将TypeNameWebApplication1更改为项目名称,将WebForm8为页面名称。

Finally :To test this code you could create a new folder in your project and add some images to it then in your database in the EvtImage column store them like this: \\NewFolder1\\yourfirstpicinnewfolder.png and... . 最后 :要测试此代码,您可以在项目中创建一个新文件夹并向其中添加一些图像,然后在您的数据库中的EvtImage列中存储它们: \\NewFolder1\\yourfirstpicinnewfolder.png和.... If you do this steps your images should be shown beside the other fields in the Repeater . 如果执行此步骤,您的图像应显示在Repeater的其他字段旁边。

If your image is being stored as a string database64 the database it should look like: "data:image/png;base64,dataImage" . 如果您的图像存储为字符串database64,则数据库应如下所示:“data:image / png; base64,dataImage”。 Otherwise you must convert your byte array (image in bytes) in database64 string and write to the bank so : "data:image/png;base64,dataImage". 否则,您必须在database64字符串中转换字节数组(以字节为单位的图像)并写入存储区,以便:“data:image / png; base64,dataImage”。

Where DataImage will be the conversion data. DataImage将成为转换数据。 In asp.net you should to use Convert.ToBase64String(byte[]). 在asp.net中你应该使用Convert.ToBase64String(byte [])。

https://www.base64-image.de/tutorial https://www.base64-image.de/tutorial

Using a string is fine. 使用字符串很好。 I recommend you save the virtual path of the image in the database; 我建议您在数据库中保存图像的虚拟路径; meaning the path .net can resolve to a physical path on your server. 意思是路径.net可以解析为服务器上的物理路径。 Eg 例如

~/Images/myImage.png 〜/图片/ myImage.png

where "Images" is a folder in the root of your .net project. 其中“Images”是.net项目根目录中的文件夹。

Then you can display the image by using 然后您可以使用显示图像

<asp:Image ID="label6" runat="server" ImageUrl='<%# ResolveUrl(Bind("EvtImage")) %>' />

如果图像保存在您的解决方案中

<%# Eval("EvtImage", "~/{0}") %>

You can save the image file as string indicating the path of Image being saved in the server folder. 您可以将图像文件另存为字符串,指示要保存在服务器文件夹中的Image的路径。

This is my implementation using MVC, you may need a little bit of modification, but I think most of the parts are just the same. 这是我使用MVC的实现,你可能需要一些修改,但我认为大多数部分都是一样的。

The View page: 查看页面:

<input id="EvtImage" title="Upload An Event Image" type="file" name="EvtImage" required="true" />
<img width="160" height="90" id="preview" src="#" alt="preview upload" hidden />

Use the ViewModel to store the Image : 使用ViewModel存储Image:

 public HttpPostedFileBase EvtImage { get; set; }
 // other fields in your model
 ....

And then at the Controller class, bind the ViewModel at the place receiving your submitted form 然后在Controller类中,将ViewModel绑定在接收提交的表单的位置

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(YourViewModel model)
{
    var imgName = Path.GetFileName(model.EvtImage.FileName);
    var img = new Bitmap(model.EvtImage.InputStream);
    var imgPath = "";
    // combine file name of event image and the folder path in server
    imgPath = Path.Combine(Server.MapPath("~/Images/Uploads/YourEventName"), imgName);
    img.Save(imgPath);

    cmd.Parameters.AddWithValue("@EvtImage", imgPath);

    // the rest of your implementation
    ....
}

Just an update. 只是一个更新。 I used varbinary in the end. 我最后用了varbinary。 I added the image to the database by using 我使用了将图像添加到数据库中

  if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".png")
        {
            Stream stream = postedFile.InputStream;
            BinaryReader reader = new BinaryReader(stream);
            byte[] imgByte = reader.ReadBytes((int)stream.Length);
            con = new SqlConnection("MyConnectionString");
            SqlCommand cmd = new SqlCommand("insert into Events (AspNetUsersId,EvtName,EvtType,EvtDescription,EvtDate,EvtVote, EvtImage) values (@AspNetUsersId, @EvtName, @EvtType, @EvtDescription, @EvtDate, @EvtVote, @EvtImage)", con);

            cmd.Parameters.AddWithValue("@AspNetUsersId", userId);
            cmd.Parameters.AddWithValue("@EvtName", eventName.Text);
            cmd.Parameters.AddWithValue("@EvtType", eventType.Text);
            cmd.Parameters.AddWithValue("@EvtDescription", eventDescription.Text);
            cmd.Parameters.AddWithValue("@EvtDate", datetimepicker.Value);
            cmd.Parameters.AddWithValue("@EvtVote", 0);
            cmd.Parameters.Add("@EvtImage", SqlDbType.VarBinary).Value = imgByte;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }

And displayed it in an image tag by using 并通过使用将其显示在图像标签中

            byte[] imgByte = null;
        con = new SqlConnection("MyConnectionString");
        SqlCommand cmd = new SqlCommand("SELECT * FROM Events", con);
        con.Open();
        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            imgByte = (byte[])(dr["EvtImage"]);
            string str = Convert.ToBase64String(imgByte);
            imageTest.Src = "data:Image/png;base64," + str;
        }

Front-End code: 前端代码:

<img runat="server" id="imageTest" src="imageIDtagName" />

Thanks for everyone's help 谢谢大家的帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM