简体   繁体   中英

asp.net upload an image

I have an asp.net web forms site, I am looking to create a control that allows the user to browse for an image then save the image into the database. I know that saving images into a database is bad practice, but thats what I've been told to do!

Does anyone have any suggestions for the best approach to do this?

thanks

Essentially all you need is a FileUpload control and some code to save it to the database. (And you'll want to do some input checking as well, naturally.) There's a pretty old tutorial which explains the concept well here . This one is a little more recent. But there's no shortage of others .

from a sample:

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

There is fileupload tool available in toolbox. You just have to writ the below code in the click event of button..

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

and I hope you have an image column in your database so then just insert the string sl1 in your insert query..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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