2013-11-23 102 views
0

我有一个数据库列'图像'可以保存二进制数据,由于某种原因图像不想上传。这行的也拉错的代码的任何异常或aything:asp.net:上传图像到SQL使用imageupload

这里是代码

protected void BtnAdd_Click(object sender, EventArgs e) 
    { 
    string imgpath = FileUploadImage.FileName.ToString(); 
    DBConnectivity.Add(imgpath); 
    } 
here is the DBCoectivity Class: 
public static void Add(string imgpath) 
    { 
     byte[] imgbt = null; 
     FileStream fstream = new FileStream(imgpath, FileMode.Open, FileAccess.Read); 
     BinaryReader BR = new BinaryReader(fstream); 
     imgbt = BR.ReadBytes((int)fstream.Length); 

     SqlConnection myConnection = GetConnection(); 
     string myQuery = "INSERT INTO images(imagePath) VALUES (@IMG)"; 
     SqlCommand myCommand = new SqlCommand(myQuery, myConnection); 
     try 
     { 
      myConnection.Open(); 
      myCommand.Parameters.Add(new SqlParameter("@IMG",imgbt)); 
      myCommand.ExecuteNonQuery(); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine("Exception in DBHandler", ex); 
     } 
     finally 
     { 
      myConnection.Close(); 
     } 
    } 

回答

1

这个片段的提取物为我工作:

byte[] imgbt = null; 

if (FileUploadImage.HasFile) 
{ 
    Stream photoStream = FileUploadImage.PostedFile.InputStream; 
    imgbt = new byte[FileUploadImage.PostedFile.ContentLength]; 
    photoStream.Read(imgbt, 0, FileUploadImage.PostedFile.ContentLength); 
} 

而且,你插入图像的名字(作为参数拼写错误作为参数添加方法和错误的变量名称选择,因为它不是一个路径)到数据库,而不是二进制数据。它应该阅读:

string myQuery = "INSERT INTO images(imgbt) VALUES (@IMG)"; 

下面是一个示例教程,更好地解释它:

File Upload with ASP.NET

+0

我不完全了解与教程链接此代码 – user2158735

+0

更新应答。 – IrishChieftain