2014年7月13日 星期日

[RESOLVED] saving an image


i have a FileUpload control which browses the path of the image


but i want to save the image when clicking save in the form of byte in the database how could that happen. i don't want an upload button



http://www.aspsnippets.com/Articles/How-to-save-insert-Image-in-Database-in-ASPNet-using-C-and-VBNet.aspx


from above link , remove the upload button and use the code in your submit button.



what is going wrong with this code?and what is it missing?


byte[] FileUpload1 = null;

if (FileUpload1.FileName != null && FileUpload1.FileName != "")

{

System.IO.FileInfo file = new System.IO.FileInfo(FileUpload1.PostedFile.FileName);

attachmentExtension = file.Extension.Remove(0, 1).ToUpper();


FileUpload1 = new byte[FileUpload1.PostedFile.ContentLength];

HttpPostedFile uploadedImage = FileUpload1.PostedFile;

uploadedImage.InputStream.Read(FileUpload1, 0, (int)FileUpload1.PostedFile.ContentLength);



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

//Set the contenttype based on File Extension
switch(ext)
{
case ".jpg":
contenttype = "image/jpg";
break;
case ".png":
contenttype = "image/png";
break;
case ".gif":
contenttype = "image/gif";
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 = "insert into tblFiles(Name, ContentType, Data)" +
" values (@Name, @ContentType, @Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value
= contenttype;
cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
lblMessage.ForeColor = System.Drawing.Color.Green;
lblMessage.Text = "File Uploaded Successfully";
}
else
{
lblMessage.ForeColor = System.Drawing.Color.Red;
lblMessage.Text = "File format not recognised.";
}



Please check below link :


http://www.codeproject.com/Articles/33310/C-Save-and-Load-Image-from-Database



Don't Forget to MARK AS ANSWER !



Thank you


沒有留言:

張貼留言