【发布时间】:2012-12-15 22:25:42
【问题描述】:
我有一个 asp.net 网络表单站点,我希望创建一个控件,允许用户浏览图像然后将图像保存到数据库中。我知道将图像保存到数据库中是不好的做法,但这就是我被告知要做的!
有人对最好的方法有什么建议吗?
谢谢
【问题讨论】:
标签: c# asp.net file-upload
我有一个 asp.net 网络表单站点,我希望创建一个控件,允许用户浏览图像然后将图像保存到数据库中。我知道将图像保存到数据库中是不好的做法,但这就是我被告知要做的!
有人对最好的方法有什么建议吗?
谢谢
【问题讨论】:
标签: c# asp.net file-upload
基本上您只需要一个FileUpload 控件和一些将其保存到数据库的代码。 (当然,您还需要进行一些输入检查。)有一个相当古老的教程很好地解释了这个概念here。 This one 是最近的一点。但是有no shortage of others。
【讨论】:
来自样本:
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();
【讨论】:
工具箱中有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..
【讨论】: