简体   繁体   English

使用表单视图在asp.net中将图像插入数据库

[英]Using Form View to insert image into database in asp.net

I have a problem to insert the image into the database.我在将图像插入数据库时​​遇到问题。 My image is failed to insert into the database.我的图像插入数据库失败。

In my .aspx file, I have this code:在我的 .aspx 文件中,我有以下代码:

<asp:FormView ID="test" runat="server" DefaultMode="Insert" InsertMethod="test_InsertItem" ItemType="Inventory.Models.pic" DataKeyNames="Id">
    <InsertItemTemplate>
        <asp:Image ID="Image1" runat="server" ImageUrl='<%# Bind("picture") %>' Height = "150" Width = "150" /><br />
        <asp:FileUpload ID="FileUpload1" runat="server"/>
        <asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="UploadFile" /><br /><br />

        <asp:Button ID="Button1" runat="server" Text="Create" CommandName="Insert"/><br /><br />
    </InsertItemTemplate>
</asp:FormView>

Then I have these in my .aspx.cs file:然后我的 .aspx.cs 文件中有这些:

protected void UploadFile(object sender, EventArgs e)
{
    FileUpload FileUpload1 = (FileUpload)test.FindControl("FileUpload1");
    Image Image1 = (Image)test.FindControl("Image1");

    if (FileUpload1.HasFile)
    {
        try
        {
            string filename = Path.GetFileName(FileUpload1.FileName);
            FileUpload1.SaveAs(Server.MapPath("~/") + filename);

            Image1.ImageUrl = Path.GetFileName(FileUpload1.FileName);
         }
         catch(Exception ex)
         {

         }
    }
}

public void test_InsertItem()
{
    pic item = new pic();
    TryUpdateModel(item);
    if (ModelState.IsValid)
    {
        TestEntities _db = new TestEntities();
        _db.pics.Add(item);
        _db.SaveChanges();
    }
}

And this as my database code:这是我的数据库代码:

CREATE TABLE [dbo].[pic]
(
    [Id] INT NOT NULL PRIMARY KEY IDENTITY, 
    [picture] IMAGE NULL
)

It works well when I using textbox to save the text into the database but when comes to image it's gone wrong.当我使用文本框将文本保存到数据库中时它运行良好,但是当涉及到图像时它出错了。 I wish to store the whole image into the database but not the image URL.我希望将整个图像存储到数据库中,而不是图像 URL。 How can I do that?我怎样才能做到这一点?

You should not use image type, you should be using varbinary instead.您不应该使用image类型,而应该使用varbinary The image type will be removed in future version. image类型将在未来版本中删除。 You can find more information here .您可以在此处找到更多信息。

As for you code, it'll be a bit easier.至于你的代码,它会更容易一些。

var image = File.ReadAllBytes(path-to-image);

Then your entity should have corresponding byte[] which will allow you to place into the database.然后你的实体应该有相应的byte[]这将允许你放入数据库。 You cannot use FileStream either for Entity Framework it will simply leverage a varbinary unless something has changed.您不能将FileStream用于实体框架,它只会利用varbinary除非发生了变化。

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

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