I have an error that I can’t fix … I really don’t know why .
I’m using this code tu upload a file in my database, i want to use the BLOB now .
if (FileUpload1.HasFile)
try
{
//FileUpload1.SaveAs("C:\\inetpub\\wwwroot\\ClientPortalCs\\"
//+ GetTheCurrentDirectory(MyTreeView.SelectedNode)
//+ "\\" + FileUpload1.FileName);
//LabelFile.Text = "File name: " +
//FileUpload1.PostedFile.FileName + "<br>" +
//FileUpload1.PostedFile.ContentLength + " kb<br>" +
//"Content type: " + FileUpload1.PostedFile.ContentType;
dbConnection.Open();
dynamic queryString = ("INSERT INTO Files (Name,Path,UserUpload,Date,Data) VALUES ('"
+ FileUpload1.FileName + "','" + GetTheCurrentDirectory(MyTreeView.SelectedNode) + "','" + Request.Cookies["UserSettings"]["UserName"] + "','" + DateTime.Now + "','" + FileUpload1.FileBytes + "' );"
+ "SELECT CAST(scope_identity() AS int)");
SqlCommand theCommand1 = new SqlCommand(queryString, dbConnection);
int newFid = (Int32)theCommand1.ExecuteScalar();
dynamic queryStringFolder = ("INSERT INTO FILES_FOLDERS (Folder_Id,File_Id) VALUES ('"
+ MyTreeView.SelectedValue + "'," + "'" + newFid + "')");
theCommand1 = new SqlCommand(queryStringFolder, dbConnection);
theCommand1.ExecuteNonQuery();
dbConnection.Close();
}
In my database the field DATA in the table files is a varbinary(max) .
The parameter for DATA field in the query is the bytes of the file I try to upload .
The error occured is :
“Error Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. “
Can someone tell me why ?
Thank you very much .
The problem, I think, is that you are passing in the byte [] of your image as a string because you are enclosing it in single quotes.
Remove the single quotes around here:
One more recommendation: Use parameters for your queries. You’ll save yourself from sql injection attacks, your queries may run faster and you’ll eliminate this kind of mistakes in the future.
UPDATE – using parameters: