从存储在SQL Server数据库中的数据路径下载图像文件

时间:2014-05-18 15:20:15

标签: c# asp.net sql-server web-applications

我正在创建一个Web表单应用程序,允许用户将图像文件上载到文件夹并将其路径存储在数据库中。有一个由图像路径填充的数据列表。我希望从数据列表中选择图像时下载图像的功能。我是新手,并没有从其他问题得到明确的指导。

请帮帮我。

以下是我上传文件的代码

try
{
    if (FileUploadzz.HasFile)
    {

        Guid g = Guid.NewGuid();
        string strguid = g.ToString();
        string uniqueString = strguid + FileUploadzz.FileName;

        FileUploadzz.SaveAs(Server.MapPath(@"~\AllUploads\AllUserImages\" + uniqueString));
        DataClasses1DataContext db2 = new DataClasses1DataContext();
        Picture p = new Picture();
        p.picturePath = "http://localhost:12237/AllUploads//AllUserImages/" + uniqueString;

        db2.Pictures.InsertOnSubmit(p);
        db2.SubmitChanges();
    }
}
catch (Exception)
{
    throw;
}

我的datalist itemtemplate中有一个按钮,我想用它来下载特定图像,单击按钮时我需要帮助下载图像。我有图像控件和datalist项目模板中的按钮(button1)。我已经用图像成功地填充了我的数据主义者。请让我知道如何在该按钮1的OnCLlick事件上下载该图像。

1 个答案:

答案 0 :(得分:0)

此代码的工作方式与传递和映像id到函数和w.r.t的方式类似。你可以获取特定的图像。这段代码就像一个基础。如果你想同时获取所有图像,那么你仍然可以使用while循环。您可以逐个进行反序列化。因此,根据您的目的,需要进行小的改动。

 private System.Windows.Forms.PictureBox picImage;   

 SqlConnection con = new SqlConnection(GetConnectionString());

    SqlCommand cmd = new SqlCommand("ReadImage", con);

    cmd.CommandType = CommandType.StoredProcedure; 

    cmd.Parameters.Add("@imgId", SqlDbType.Int).Value = Convert.ToInt32(cmbImageID.SelectedValue.ToString());



     SqlDataAdapter adp = new SqlDataAdapter(cmd);

DataTable dt = new DataTable();

try
   {
    if (con.State == ConnectionState.Closed)

    con.Open();
     adp.Fill(dt);

   if (dt.Rows.Count > 0)
       {
        MemoryStream ms = new MemoryStream((byte[])dt.Rows[0]["ImageData"]);

        picImage.Image = Image.FromStream(ms);

        picImage.Image.Save(@"Complete path of location", ImageFormat.Jpeg);
                    }
                }
                catch (Exception ex)//catch if any error occur
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (con.State == ConnectionState.Open)//check whether connection to database is open or not
                        con.Close();
                }
            }