【问题标题】:asp.net upload an imageasp.net 上传图片
【发布时间】:2012-12-15 22:25:42
【问题描述】:

我有一个 asp.net 网络表单站点,我希望创建一个控件,允许用户浏览图像然后将图像保存到数据库中。我知道将图像保存到数据库中是不好的做法,但这就是我被告知要做的!

有人对最好的方法有什么建议吗?

谢谢

【问题讨论】:

    标签: c# asp.net file-upload


    【解决方案1】:

    基本上您只需要一个FileUpload 控件和一些将其保存到数据库的代码。 (当然,您还需要进行一些输入检查。)有一个相当古老的教程很好地解释了这个概念hereThis one 是最近的一点。但是有no shortage of others

    【讨论】:

      【解决方案2】:

      来自样本:

      var intDoccumentLength = FileUpload1.PostedFile.ContentLength;
      var newDocument = new byte[intDoccumentLength];
      
      var stream = FileUpload1.PostedFile.InputStream;
      stream.Read(newDocument, 0, intDoccumentLength);
      var sqlConnection = new SqlConnection(sqlConnectionString);
      sqlConnection.Open();
      
      var sqlQuery = "INSERT INTO dbo.DocumentData (DocName, DocBytes, DocData, DocCreatedAt) VALUES (@DocName, @DocBytes, @DocData, @DocCreatedAt);"
                                 + "SELECT CAST(SCOPE_IDENTITY() AS INT)";
      
      sqlCommand = new SqlCommand(sqlQuery, sqlConnection);
      sqlCommand.Parameters.Add("@DocName", SqlDbType.NVarChar, 255);
      sqlCommand.Parameters.Add("@DocBytes", SqlDbType.Int);
      sqlCommand.Parameters.Add("@DocData", SqlDbType.VarBinary);
      sqlCommand.Parameters.Add("@DocCreatedAt", SqlDbType.DateTime);
      
      sqlCommand.Parameters["@DocName"].Value = FileUpload1.PostedFile.FileName;
      sqlCommand.Parameters["@DocBytes"].Value = intDoccumentLength;
      sqlCommand.Parameters["@DocData"].Value = newDocument;
      sqlCommand.Parameters["@DocCreatedAt"].Value = DateTime.Now;
      
      var newDocumentId = (Int32) sqlCommand.ExecuteScalar();
      sqlConnection.Close();
      

      【讨论】:

        【解决方案3】:

        工具箱中有fileupload 工具可用。您只需在按钮的单击事件中编写以下代码..

        string filename = FileUpload1.FileName.ToString();
                 if (filename != "")
                    {
        
                        ImageName = FileUpload1.FileName.ToString();
        
                        ImagePath = Server.MapPath("Images");
                        SaveLocation = ImagePath + "\\" + ImageName;
                        SaveLocation1 = "~/Image/" + ImageName;
                        sl1 = "Images/" + ImageName;
                        FileUpload1.PostedFile.SaveAs(SaveLocation);
                    }
        

        我希望你的数据库中有一个图像列,所以只需在插入查询中插入字符串 sl1..

        【讨论】:

        • 并且不要忘记在执行该查询后从服务器中删除文件。否则可能会变得混乱。 ;-)
        猜你喜欢
        • 2011-05-22
        • 2018-04-17
        • 2018-05-02
        • 2023-03-07
        • 2016-06-24
        • 1970-01-01
        • 2022-12-17
        • 2014-07-27
        • 2018-04-21
        相关资源
        最近更新 更多