2015-07-20 44 views
-1

我想要做的是將我的圖像添加到我的sql數據庫。目前,我有這樣的代碼:將上傳輸入圖像添加到數據庫

SqlConnection con = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=Authorship;Integrated Security =True"); 
SqlCommand cmd = new SqlCommand(); 
protected void Button1_Click(object sender, EventArgs e) 
{ 

    if (Page.IsValid) 
    { 
     cmd.Connection = con; //assigning connection to command 
     cmd.CommandType = CommandType.Text; //representing type of command 
     //cmd.CommandText = "INSERT INTO UserDetails (Fname,Lname,Email,Password,Gender,Dob,Mobile,Address) values 
     // (@Fname,@Lname,@Email,@Password,@Gender,@Dob,@Mobile,@Address)"; 
     cmd.CommandText = "INSERT INTO Products values(@Name,@Description,@Image,@Quantity,@ProductPrice)"; 

     //adding parameters with value 
     cmd.Parameters.AddWithValue("@Name", TextBox1.Text); 
     cmd.Parameters.AddWithValue("@Description", TextBox2.Text); 
     cmd.Parameters.AddWithValue("@Image", FileUpload1); 
     cmd.Parameters.AddWithValue("@Quantity", TextBox4.Text); 
     cmd.Parameters.AddWithValue("@ProductPrice", TextBox4.Text); 

     con.Open(); //opening connection 
     cmd.ExecuteNonQuery(); //executing query 
     con.Close(); //closing connection 
     Label1.Text = "Added Successfully.."; 

    } 
    else 
    { 
     Label1.Text = "Not successful"; 
    } 

我有此錯誤:

No mapping exists from object type System.Web.UI.WebControls.FileUpload to a known managed provider native type.

任何想法,我應該怎麼在我的

cmd.Parameters.AddWithValue("@Image", FileUpload1.????); 

寫謝謝!

+0

什麼是'型您嘗試插入的圖像列? –

+0

在數據庫中?數據類型是圖像。 –

+0

即時通訊試圖插入JPG文件 –

回答

0

您需要獲得var input = FileUpload1.FileBytes。 那麼這些內容推到字符串:

// Copy the byte array to a string. 
for (int loop = 0; loop < input.length; loop++) { 
    displayString = displayString + input[loop].ToString(); 
} 

然後將其發送給數據庫:

cmd.Parameters.AddWithValue("@Image", displayString);

由於@Soner格尼爾建議在意見:

By the way, image type will be removed future SQL Server versions. Consider to change your column type to varbinary(max).