I'm trying to update my profile picture using varbinary (SQL Server 2008). It don't seem to update the picture that I put in the fileupload. Below is the code I use to update my profile picture. Do help me take a look on which part of my coding did I do wrongly. Thanks.
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();
}
}
XARS
try this:
...
//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 + "'";
...
You can load a file directly with sql.
来源:https://stackoverflow.com/questions/16892710/unable-to-update-profile-picture-using-varbinary