2011-03-25 126 views
1

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

有没有人有任何建议最好的方法来做到这一点?

感谢

回答

4

来自样本:

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(); 
6

基本上所有你需要的是一个FileUpload控制和一些代码,将其保存到数据库中。 (而且你自然也想做一些输入检查。)有一个很老的教程,它很好地解释了这个概念hereThis one稍微近一点。但有no shortage of others

0

工具箱中有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 ..

+1

并且不要忘记在执行该查询后从服务器删除文件。否则会变得混乱。 ;-) – Koen 2011-03-25 12:18:17