繁体   English   中英

asp.net上传图片

[英]asp.net upload an image

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

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

谢谢

本质上,您只需要一个FileUpload控件和一些代码即可将其保存到数据库。 (当然,您自然也要进行一些输入检查。)有一个很旧的教程在这里很好地解释了这个概念。 是最近一点。 但是其他人并不缺乏

从一个样本:

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工具。 您只需要在button的click事件中编写以下代码即可。

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);
            }

我希望您的数据库中有一个image列,因此只需在插入查询中插入字符串sl1。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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