简体   繁体   English

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

[英]How do I save the BLOB of an image into a sql database without saving it to the filesystem first?

what I've been trying to find out is how I can store the BLOB of an image into my database without saving it to the filesystem first, so directly from the server's memory. 我一直试图找出的是如何将图像的BLOB存储到数据库中而不先将其保存到文件系统中,而是直接从服务器的内存中保存。

I use an sql server and among other form information I have 2 images that need to be stored in the database. 我使用sql服务器,除其他表单信息外,我还有2张需要存储在数据库中的图像。 I would also like to know how I can read them out and convert them back to images. 我也想知道如何读取它们并将它们转换回图像。

In the db I have "Thumbnail" which is of type "image". 在数据库中,我有类型为“图像”的“缩略图”。 That should be correct if I'm not wrong. 如果我没看错,那应该是正确的。

For the image upload I use the following asp control: 对于图像上传,我使用以下asp控件:

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

I have never done anything like this as I am quite new to working with databases especially together with websites. 我从来没有做过这样的事情,因为我对使用数据库(尤其是与网站一起使用)非常陌生。

Oh, and sorry if this question has been asked and answered already. 哦,很抱歉,是否已经有人问过这个问题。

Thanks in advance! 提前致谢!

[edit] [编辑]

My entire code: 我的整个代码:

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);
    }
}

You can save the returned byte array from FileUpload.FileBytes . 您可以从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();
     }
   }
}

EDIT: 编辑:

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();
}

暂无
暂无

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

相关问题 如何将内存位图保存到 ZipArchive 而不先将位图保存到文件系统? - How do I save an in memory Bitmap to a ZipArchive without saving the Bitmap to the file system first? 如何将图片网址保存在数据库中? - How do I save image URL in database? 如何将图像保存到 Azure Blob 并使用特定字段命名并返回 Blob Url 并将其保存到 .net core 2.2 中的数据库 - How can i save an image to a Azure Blob and name it with specific fields and return the Blob Url and save it to database in .net core 2.2 如何将信息从未绑定的datagridview保存到SQL数据库 - How do I save info from an unbound datagridview to SQL database 如何在不保存图像的情况下将Base 64编码的图像数据作为图像插入表中? - How do i insert Base 64 encoded image data as an image in table without saving the image? 从openfiledialog获取名称后,如何在访问数据库中存储映像BLOB? - How do I store a image BLOB in an access database after getting the name from openfiledialog? 如何在EF上下文中保存对象并检查其是否存在,而不将其保存到数据库? - How to save an object in EF context and check if it exists, without saving it to the database? 将图像保存到 SQL Server 数据库中 - Saving Image into SQL Server database 如何将调整大小的图像保存到 ASP.NET 核心应用程序中的 Azure Blob 存储? - How do I save my resized image to my Azure Blob Storage in my ASP.NET Core Application? 想要将图像保存到文件夹并将 url 保存在数据库中 - Want to save a image to a folder and saving the url in database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM