2013-11-23 53 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