如何将图像的BLOB保存到sql数据库而不将其保存到文件系统?

时间:2012-08-14 12:02:39

标签: c# .net sql-server upload blob

我一直试图找出的是如何将图像的BLOB存储到我的数据库中,而不是先将其保存到文件系统,直接从服务器的内存中保存。

我使用sql server和其他表单信息,我有2个图像需要存储在数据库中。我也想知道如何阅读它们并将它们转换回图像。

在db中,我有“Thumbnail”,类型为“image”。如果我没错,那应该是正确的。

对于图像上传,我使用以下asp控件:

<asp:FileUpload ID="_imageUpload" runat="server" />

我从未做过这样的事情,因为我很擅长使用数据库,特别是与网站一起工作。

哦,对不起,如果这个问题已被提出并已经回答过了。

提前致谢!

[编辑]

我的整个代码:

protected void _uploadImageBtn_Click(object sender, EventArgs e)
{
    string extension;

    // checks if file exists
    if (!_imageUpload.HasFile)
    {
        _resultLbl.Text = "Please, Select a File!";
        return;
    }

    // checks file extension
    extension = System.IO.Path.GetExtension(_imageUpload.FileName).ToLower();

    if (!extension.Equals(".jpg") && !extension.Equals(".jpeg") && !extension.Equals(".png"))
    {
        _resultLbl.Text = "Only image files (.JPGs and .PNGs) are allowed.";
        return;
    }

    // checks if image dimensions are valid
    if (!ValidateFileDimensions(140, 152))
    {
        _resultLbl.Text = "Maximum allowed dimensions are: width 1520px and height <= 140px.";
        return;
    }

    int fileLen;
    string displayString = "";

    // Get the length of the file.
    fileLen = _imageUpload.PostedFile.ContentLength;

    // Create a byte array to hold the contents of the file.
    byte[] input = new byte[fileLen - 1];
    input = _imageUpload.FileBytes;

    // Copy the byte array to a string.
    for (int loop1 = 0; loop1 < fileLen; loop1++)
    {
        displayString = displayString + input[loop1].ToString();
    }

    try
    {

        SqlConnection sqlCn = new SqlConnection("Data Source=localhost;Initial Catalog=database;User ID=user;Password=pw");

        string qry = "INSERT INTO Project (thumbnail) VALUES (@thumbnail)";

        SqlCommand sqlCom = new SqlCommand(qry, sqlCn);

        sqlCom.Parameters.Add("@thumbnail", SqlDbType.Image, input.Length).Value = input;

        sqlCn.Open();
        sqlCom.ExecuteNonQuery();
        sqlCn.Close();

    }

    catch (Exception)
    {
        (...)
    }
}

public bool ValidateFileDimensions(int aHeight, int aWidth)
{
    using (System.Drawing.Image image = System.Drawing.Image.FromStream(_imageUpload.PostedFile.InputStream))
    {
        return (image.Height == aHeight && image.Width == aWidth);
    }
}

1 个答案:

答案 0 :(得分:4)

您可以从FileUpload.FileBytes保存返回的字节数组。

if(_imageUpload.HasFile)
{
 byte[] imageData = _imageUpload.FileBytes;

 using(SqlConnection sqlCn = new SqlConnection("Server=localhost;database=databaseName;uid=userName;pwd=password"))
  {
    string qry = "INSERT INTO Project (thumbnail) VALUES (@thumbnail)";
    using(SqlCommand sqlCom = new SqlCommand(qry, sqlCn))
     {
       sqlCom.Parameters.Add("@thumbnail",
                              SqlDbType.Image,
                              imageData.Length).Value=imageData;
       sqlCn.Open();
       sqlCom.ExecuteNonQuery();
       sqlCn.Close();
     }
   }
}

编辑:

protected void _uploadImageBtn_Click(object sender, EventArgs e)
{
    string extension;

    // checks if file exists
    if (!_imageUpload.HasFile)
    {
        _resultLbl.Text = "Please, Select a File!";
        return;
    }

    // checks file extension
    extension = System.IO.Path.GetExtension(_imageUpload.FileName).ToLower();

    if (!extension.Equals(".jpg") && !extension.Equals(".jpeg") && !extension.Equals(".png"))
    {
        _resultLbl.Text = "Only image files (.JPGs and .PNGs) are allowed.";
        return;
    }

    // checks if image dimensions are valid
    if (!ValidateFileDimensions(140, 152))
    {
        _resultLbl.Text = "Maximum allowed dimensions are: width 1520px and height <= 140px.";
        return;
    }


    byte []input = _imageUpload.FileBytes;
    SqlConnection sqlCn = new SqlConnection("Data Source=localhost;Initial 
                                 Catalog=database;User ID=user;Password=pw");

    string qry = "INSERT INTO Project (thumbnail) VALUES (@thumbnail)";
    SqlCommand sqlCom = new SqlCommand(qry, sqlCn);
    sqlCom.Parameters.Add("@thumbnail", SqlDbType.Image, input.Length).Value = input;
    sqlCn.Open();
    sqlCom.ExecuteNonQuery();
    sqlCn.Close();
}