Web表单 - 将图像存储在数据库中

时间:2015-04-17 17:44:58

标签: asp.net

我正在WebForm中编写一个程序。我正在尝试编写代码,使用户能够上传图像文件,将图像存储在SQL Server中,同时在页面中显示它。我怎样才能做到这一点? 我知道如何存储Text.box,但我没有为图像做到这一点。我是初学程序员。  我将非常感谢你的帮助。

protected void UploadButton_Click(object sender, EventArgs e)
{
    if (FileUploadControl.HasFile)
    {
        try
        {
            if(FileUploadControl.PostedFile.ContentType == "image/jpeg")
            {
                if(FileUploadControl.PostedFile.ContentLength < 102400)
                {
                    string filename = Path.GetFileName(FileUploadControl.FileName);
                    FileUploadControl.SaveAs(Server.MapPath("~/Images/") + filename);
                    StatusLabel.Text = "Upload status: File uploaded!";
                }
                else
                    StatusLabel.Text = "Upload status: The file has to be less than 100 kb!";
            }
            else
                StatusLabel.Text = "Upload status: Only JPEG files are accepted!";
        }
        catch(Exception ex)
        {
            StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        }   
    }
}

1 个答案:

答案 0 :(得分:1)

以下是示例代码,请尝试:

System.Drawing.Image image;
System.IO.MemoryStream imageStream;
byte[] imageBytes;

// image = your image object
imageStream = new System.IO.MemoryStream();
image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg); // Use whatever format your image is.
imageBytes = imageStream.ToArray();
// Save imageBytes to a DB column of type VARBINARY(MAX)

你也需要这个:

use System.Drawing.Image.FromStream(System.IO.Stream stream).