繁体   English   中英

在数据库中插入图像

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM