[英]insert Image in database
我是asp.net和數據庫的新手! 我正在嘗試通過文件上傳控件將圖像保存到數據庫中。 我已經嘗試過,但是單擊提交按鈕后它不起作用,數據沒有添加到數據庫中,也沒有顯示任何錯誤! 這是我嘗試過的代碼
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile && Page.IsValid) //fileUpload and submit
{
string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName);
if (fileExtension.ToLower() != ".jpg")
{
Labelupload.Text = "Only Files with .jpg extension are allowed";
Labelupload.ForeColor = System.Drawing.Color.Red;
}
else
{
FileUpload1.SaveAs(Server.MapPath("~/Uploads/" + FileUpload1.FileName));
Labelupload.Text = "File Uploaded";
Labelupload.ForeColor = System.Drawing.Color.DeepSkyBlue;
LabelSubmit.Text = "Submitted Succesfully";
LabelSubmit.ForeColor = System.Drawing.Color.DeepSkyBlue;
}
}
else
{
Labelupload.Text = "Please select a file";
Labelupload.ForeColor = System.Drawing.Color.Red;
LabelSubmit.Text = "Failed to Submit";
LabelSubmit.ForeColor = System.Drawing.Color.Red;
}
// insert into database
Work obj = new Work();
/* Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);*/
obj.listItem_1 = DropDownList1.SelectedValue;
obj.listItem_2 = DropDownList2.SelectedValue;
obj.Description = TextBoxdescription.Text;
obj.Date = TextBoxdate.Text;
//obj.UploadedImage = bytes;
int k = obj.insertmethod();
TextBoxdescription.Text = "";
}
這是包含insertmethod()
邏輯的Work
類:
public class Work
{
Clssqlconnection obj = new Clssqlconnection();
public string listItem_1 { get; set; }
public string listItem_2 { get; set; }
public string Description { get; set; }
public string Date { get; set; }
//public Byte[] UploadedImage { get; set; }
public int insertmethod()
{
obj.str = @"insert into [assign_Work] (listItem_1, listItem_2, Description, Date, UploadedImage)" +
"values('" + listItem_1 + "','" + listItem_2 + "','" + Description + "','" + Date + "','" + UploadedImage + "')";
return obj.ExecuteNonQuery();
}
}
圖像需要通過參數進入數據庫。 您不能在原始SQL語句中使用它。 嘗試這個:
public int insertmethod()
{
obj.str = @"insert into [assign_Work] (listItem_1, listItem_2, Description, Date, UploadedImage)" +
"values('" + listItem_1 + "','" + listItem_2 + "','" + Description + "','" + Date + "', ?)";
obj.Parameters.AddWithValue("File", UploadedImage);
return obj.ExecuteNonQuery();
}
另外,順便說一句,您可能要考慮對所有這些值使用參數,以避免注入攻擊。 例如,如果您的“描述”字段中包含撇號怎么辦?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.