使用C#无法在数据库中上传图片

时间:2018-09-26 06:05:22

标签: c# asp.net file-upload image-uploading

image of page unreachable我正在使用c#。保存到官方数据库时出现页面无法访问错误。结果是图像。为什么?

  SqlConnection con = new SqlConnection("Data Source=name;Initial Catalog=dbname;User ID=sa;Password=pss");
    if (FileUpload1.HasFile)
   {
       string strname = FileUpload1.FileName.ToString();
        FileUpload1.PostedFile.SaveAs(Server.MapPath("~/upload/") + strname);
       con.Open();
       SqlCommand cmd = new SqlCommand("INSERT INTO image( imageurl)VALUES('" + strname + "')", con);
       cmd.ExecuteNonQuery();
       con.Close();
             }

            <div class="form-group">
           <div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
     <asp:FileUpload ID="FileUpload1" runat="server"></asp:FileUpload>
    <asp:Button ID="Button3" class="btn btn-success" runat="server" 
    Text="Dosya Yükle" OnClick="Button3_Click"></asp:Button>
                [![enter image description here][1]][1] </div>
                  </div>

1 个答案:

答案 0 :(得分:0)

要将图像插入database,必须将该字节保存在database上。

但是您在urlImage上保存了database,您是否有特定原因?

保存字节的示例:

Image img = Image.FromFile(@"C:\Lenna.jpg");
byte[] arr;
using (MemoryStream ms = new MemoryStream())
{
    img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
    arr =  ms.ToArray();
}

之后,您将有一个数组将其保存到数据库中。