ASP.NET store Image in SQL and retrieve for Asp:Image

前端 未结 7 852
挽巷
挽巷 2020-12-01 17:41

I am looking to fileupload a picture jpeg,gif,etc into an SQL database on an updateprofilepicture page. Then on the profile page, I want to retrieve the image from an sql da

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-01 18:16

    protected void Page_Load(object sender, EventArgs e) {
        GridView1.DataSourceID = "";
        GridView1.DataSource = SqlDataSource1;
        GridView1.DataBind();
    }
    
    protected void btnSubmit_Click(object sender, EventArgs e) {
        string strImageName = txtImageName.Text.ToString();
    
        if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "") {
            byte[] imageSize = new byte[FileUpload1.PostedFile.ContentLength];
            HttpPostedFile uploadedImage = FileUpload1.PostedFile;
            uploadedImage.InputStream.Read(imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);
    
            // Create SQL Connection
            SqlConnection con = new SqlConnection();
            con.ConnectionString = "Data Source=RND3" + "\\" + "SQLEXPRESS;Initial Catalog=SSSolutionFiles;Integrated Security=True";
    
            // Create SQL Command 
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "INSERT INTO Imagess(ImageName,Image)" + " VALUES (@ImageName,@Image)";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
    
            SqlParameter ImageName = new SqlParameter("@ImageName", SqlDbType.VarChar, 50);
            ImageName.Value = strImageName.ToString();
            cmd.Parameters.Add(ImageName);
    
            SqlParameter UploadedImage = new SqlParameter("@Image", SqlDbType.Image, imageSize.Length);
            UploadedImage.Value = imageSize;
            cmd.Parameters.Add(UploadedImage);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
    
            Label1.Text = "File Uploaded";
    
            GridView1.DataSourceID = "";
            GridView1.DataSource = SqlDataSource1;
            GridView1.DataBind();
            con.Close();
        }
    }
    

提交回复
热议问题