Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Writing a file to SQL database

Status
Not open for further replies.

shaqtus123

Technical User
Sep 24, 2010
4
US
I have a website that allows users to upload files. The uploaded file is managed using a FileUpload control. Inside the SQL database the file is inserted into a field called "Attachment" which has a data type of varbinary(MAX). Whenever I try to upload the file and insert it into the database by clicking the submit button, I get an error that basically saying something like "Cannot convert type varchar to varbinary(MAX)" Heres the code:

Code:
string cmdAnnouncement = "INSERT INTO Announcements [Attachment] VALUES ('" + fileUpload.FileBytes + "')";
SqlCommand cmd = db.executeSQL(cmdAnnouncement);

I don't see what the problem is here since I'm inputting data bytes of the file into the database... can someone please tell me what the problem is?
 
Hi,
Why are you enclosing fileUpload.FileBytes in "s?
The statement as read seems to be trying to insert a literal string, that is "fileUpload.FileBytes" and not the contents of fileUpload.FileBytes




[profile]

To Paraphrase:"The Help you get is proportional to the Help you give.."
 
Yes you are sending in a literal value. Also, you should be calling a stored procedure with parameters and avoid using inline SQL.
 
it's already been said that you are using a literal string, instead of the byte array. to solve this use a parameterized query. this should be the default anyway, as there are many problem with sql injection. the code should look something like this
Code:
var command = connection.CreateCommand();
command.CommandText = "INSERT INTO Announcements [Attachment] VALUES (@file)";

var parameter = command.CreateParameter();
parameter.ParameterName = "file",
parameter.Value = fileUpload.FileBytes
command.Parameters.Add(parameter);

command.ExecuteNonQuery();

Jason Meckley
Programmer

faq855-7190
faq732-7259
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top