如何在数据库中保存图像

时间:2011-02-18 10:26:40

标签: .net asp.net

FileUpload img = (FileUpload)UploadImg;
        Byte[] imgByte = null;
        if (img.HasFile && img.PostedFile!=null)
        {
            HttpPostedFile File = UploadImg.PostedFile;
            imgByte = new Byte[File.ContentLength];
            File.InputStream.Read(imgByte, 0, File.ContentLength);
        }    **strong text**

这里我想在数据库中保存图像。所以我想将图像转换为字节数组。因为我写了上面的代码。但这里没有执行if条件

1 个答案:

答案 0 :(得分:0)

假设您的页面上有文件上传控件:

<asp:FileUpload id="UploadImg" runat="server" />
<asp:Button id="UploadButton" runat="server" Text="Upload" OnClick="UploadButton_Click" />

以下内容应该有效:

protected void UploadButton_Click(object sender, EventArgs e)
{
    if(UploadImg.HasFile)
    {
        byte[] imgByte = UploadImg.FileBytes;
        string filename = Path.GetFileName(UploadImg.FileName);
        // TODO: Save the image to the database
    }
}