2
我正嘗試使用varbinary(SQL Server 2008)更新我的個人資料圖片。它似乎沒有更新我把文件上傳的圖片。然後我嘗試將我的個人資料圖片列設置爲NULL,但它似乎也沒有工作。以下是我用於將我的個人資料圖片列更新爲NULL並使用fileupload更新個人資料圖片並將其轉換爲varbinary(MAX)的代碼。請幫我看看我做錯了什麼。謝謝!無法更新SQL Server中的varbinary(max)列
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);
string strQuery = "Update LoginRegisterOthers Set profilepic = NULL Where username = '" + username + "'";
SqlCommand cmd = new SqlCommand(strQuery);
InsertUpdateData(cmd);
//insert the file into database
//string strQuery2 = "Update LoginRegisterOthers Set profilepic = @Data Where username = @Username";
//SqlCommand cmd2 = new SqlCommand(strQuery2);
//cmd2.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
//cmd2.Parameters.Add("@Username", SqlDbType.VarChar).Value = username;
//InsertUpdateData(cmd2);
//lblUpload.ForeColor = System.Drawing.Color.Green;
//lblUpload.Text = "Profile Updated.";
Response.Redirect("MemberProfile.aspx");
}
else if (contenttype == String.Empty)
{
lblUpload.Text = "Please select your image before uploading!";
}
else
{
lblUpload.ForeColor = System.Drawing.Color.Red;
lblUpload.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();
}
}