【问题标题】:How do I save the BLOB of an image into a sql database without saving it to the filesystem first?如何将图像的 BLOB 保存到 sql 数据库中而不先将其保存到文件系统?
【发布时间】:2012-08-10 17:14:49
【问题描述】:

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

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

在数据库中,我有“图像”类型的“缩略图”。如果我没记错的话应该是对的。

对于图片上传,我使用以下 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);
    }
}

【问题讨论】:

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


    【解决方案1】:

    您可以保存来自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();
    }
    

    【讨论】:

    • 嘿,我试了几次,我只是调试它,因为 INSERT 总是失败并且发生了,因为(在你的例子中)“字节”数组不包含任何值,所以它试图填充NULL 这当然不起作用,因为它是不允许的。你确定这应该有效吗?
    • 我该怎么做?我更新了我上面的代码,所以你可以看到我在做什么
    • 我实际上已经这样做了:if (!_imageUpload.HasFile) { _resultLbl.Text = "Please, Select a File!"; return; }
    • 循环需要如何喜欢,我究竟要循环什么?
    • 您必须在 INSERT SQL(查询)中包含所有 (不为空)。类似于:INSERT INTO PROJECT (col1,col2,col3) values (@para1,para2,para3)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-13
    相关资源
    最近更新 更多