从DataBase

时间:2016-04-06 16:10:39

标签: c# sql asp.net image repeater

不确定这是否接近。 我正在使用代码

在数据库表Events中创建一个图像字段
public string EvtImage { get; set; }

首先,我甚至不确定它是否应该是一个字符串。 然后我尝试使用代码

将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);

一旦添加了这个,我试图使用代码在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>

我正在使用代码创建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();

6 个答案:

答案 0 :(得分:6)

按照以下步骤

在数据库中,你应该有,

public Byte[] EvtImage { get; set; }

声明为,

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);
}

保存时更改

<%@ 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;
        }
    }


}

要显示图像,请按以下方式创建处理程序,(根据需要更改表格/列)

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

最后在aspx中添加asp图像并添加图像URL,

$.get()

如果您有任何困难,请告诉我。

答案 1 :(得分:2)

在后面的代码中编写一个名为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);
            }
        }
    }
}

还有一个班级:

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

然后要显示此图像,您有两个选择。您可以asp:Repeater使用asp: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>

不要忘记将WebApplication1中的TypeName更改为项目名称,将WebForm8更改为页面名称。

最后:要测试此代码,您可以在项目中创建一个新文件夹并向其添加一些图像,然后在EvtImage列的数据库中存储它们,如下所示:{{ 1}}和....如果您执行此步骤,您的图片应显示在\NewFolder1\yourfirstpicinnewfolder.png

中的其他字段旁边

答案 2 :(得分:1)

如果您的图像存储为字符串database64,则数据库应如下所示:“data:image / png; base64,dataImage”。 否则,您必须在database64字符串中转换字节数组(以字节为单位的图像)并写入存储区,以便:“data:image / png; base64,dataImage”。

DataImage将成为转换数据。 在asp.net中,你应该使用Convert.ToBase64String(byte [])。

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

答案 3 :(得分:1)

使用字符串很好。我建议您在数据库中保存图像的虚拟路径;意思是路径.net可以解析为服务器上的物理路径。 E.g。

  

〜/图像/ myImage.png

其中&#34;图像&#34;是.net项目根目录中的文件夹。

然后您可以使用

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

答案 4 :(得分:0)

您可以将图像文件另存为字符串,指示要保存在服务器文件夹中的图像的路径。

这是我使用MVC的实现,您可能需要进行一些修改,但我认为大多数部分都是相同的。

查看页面:

<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 />

使用ViewModel存储图像:

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

然后在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
    ....
}

答案 5 :(得分:-1)

只是一个更新。我最后用了varbinary。我使用

将图像添加到数据库中
  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();
        }

使用

将其显示在图像标签中
            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;
        }

前端代码:

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

感谢大家的帮助

相关问题