2013-06-03 91 views
1

我正嘗試使用varbinary(SQL Server 2008)更新我的個人資料照片。它似乎沒有更新我把文件上傳的圖片。以下是我用來更新我的個人資料圖片的代碼。是否幫助我看看我編碼的哪一部分是我錯誤地做的。 謝謝。無法使用varbinary更新個人資料照片

protected void btnUpload_Click(object sender, EventArgs e) 
    { 
     String username = (String)Session["username"]; 

     string filePath = FileUpload1.PostedFile.FileName; 
     string filename = Path.GetFileName(filePath); 
     string ext = Path.GetExtension(filename); 

     string contenttype = String.Empty; 

     switch (ext) 
     { 
      case ".jpg": 
       contenttype = "image/jpg"; 
       break; 
     } 
     if (contenttype != String.Empty) 
     { 
      Stream fs = FileUpload1.PostedFile.InputStream; 

      BinaryReader br = new BinaryReader(fs); 

      Byte[] bytes = br.ReadBytes((Int32)fs.Length); 

      //insert the file into database 
      string strQuery = "Update LoginRegisterOthers Set profilepic = @Data Where username = '" + username + "'"; 
      SqlCommand cmd = new SqlCommand(strQuery); 
      cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes; 
      InsertUpdateData(cmd); 
      lblMessage.ForeColor = System.Drawing.Color.Green; 
      lblMessage.Text = "Profile Updated."; 

      Response.Redirect("MemberProfile.aspx"); 
     } 
     else if (contenttype == String.Empty) 
     { 
      lblMessage.Text = "Please select your image before uploading!"; 
     } 
     else 
     { 
      lblMessage.ForeColor = System.Drawing.Color.Red; 
      lblMessage.Text = "File format not recognised." + " Upload Image formats"; 
     } 
    } 

    private Boolean InsertUpdateData(SqlCommand cmd) 
    { 
     SqlConnection con = new SqlConnection("Data Source=localhost; Initial Catalog=project; Integrated Security=True"); 
     cmd.CommandType = CommandType.Text; 
     cmd.Connection = con; 
     try 
     { 
      con.Open(); 
      cmd.ExecuteNonQuery(); 
      return true; 
     } 
     catch (Exception ex) 
     { 
      Response.Write(ex.Message); 
      return false; 
     } 
     finally 
     { 
      con.Close(); 
      con.Dispose(); 
     } 
    } 
+0

您應該在'UPDATE'查詢中爲您的用戶名使用**參數**! –

+0

@marc_s即使我使用用戶名參數,它仍然不起作用。 – XiAnG

回答

0

試試這個:

... 

//insert the file into database 

string strQuery = "Update LoginRegisterOthers Set profilepic = (SELECT BULKCOLUMN FROM OPENROWSET(BULK N'"+filename+"', SINGLE_BLOB) AS FIle_picture) Where username = '" + username + "'"; 

... 

可以使用SQL直接加載的文件。

相關問題