Use FileUpload to upload pictures in C # to SQL database to store with image type and display considerations with the image control

Source: Internet
Author: User

When we need to store pictures in a data stream in a database rather than a file path , there are a number of factors that need to be taken into account, and different environments dictate different approaches.

1. Save the picture to the database. First, when we decided to use FileUpload upload pictures, need to consider, fileupload function is mainly to select the image on the client, and then use the FileUpload SaveAs method to save the address of the selected picture to the server-side save, Because we use the data stream to store the picture, it is not necessary to save the picture to the server side.

Second,FileUpload is not as opendialog as the. Filter method to filter the format of the picture, that is, to implement the Open dialog box, only select the format of the picture file form. So here we need to write our own code to filter the file format.


Here is the main code to upload the image:

//Upload pictures
if (fupcontractphoto.postedfile.contentlength<500000)//Limit file size of 100000 to 100K
{
string filefullname = This.fupContractPhoto.PostedFile.FileName;//File Full name
String fileName = Filefullname.substring (filefullname.lastindexof ("\ \") + 1);//File name
String type = Filename.substring (Filename.lastindexof (".") + 1);//File type
if (type. ToLower () = = "BMP" | | Type. ToLower () = = "JPG" | | Type. ToLower () = = "GIF" | | Type. ToLower () = = "png")
{
string Filefullpath=server.mappath ("~/upload") + "\ \" +filename;
This.fupContractPhoto.SaveAs (Filefullpath);
Convert a file to a data stream
FileStream fs = new FileStream (Filefullpath, FileMode.Open);//File stream
Byte[] Imagebytes=new Byte[fs. Length];//Set byte stream array size
BinaryReader br = new BinaryReader (FS);//Read Byte object
Imagebytes = Br. Readbytes (Convert.ToInt32 (fs. Length));//Byte stream is read into an array of bytes

//Assign a byte stream object to a Project object
Project. Contractphoto = imagebytes;
}

}

It is necessary to note that a field of the object type is used in the ASP. NET code page to store the image into a byte[] byte array, One instance of project object used here is the properties of Project Contractphoto. A field in the database that uses the image type stores the image that will be uploaded.

Here is the statement that interacts with the database:

First, because the picture is converted into a stream of bytes and stored in a byte array, someone would like to insert the inserted statement directly into the corresponding field in the data can, the answer is not possible . As in this form:string sql=string. Format ("INSERT INTO Project (Contractphoto) values (' {0} ')", Project. Contractphoto); With breakpoint debugging, you can see that the system.drawing is stored in the database instead of the byte stream data. So can we convert the byte stream into a binary string by convert.tobase64string ? The answer is yes, but it doesn't appear when the picture is displayed. So how do we insert data into the database? This problem has been tangled for a long time, and finally it is possible to insert the data in the database into the database in the form of a parameter by the command class. As in this form:string sql= "insert into Project (Contractphoto) VALUES (@ContractPhoto)"; Then use the SqlParameter class to organize the parameter array. Because the SqlHelper class is written by Microsoft, the ADO User database interaction provides convenience here is a concise point through this class to achieve concrete implementation.

Here is the code that implements inserting its own array data into the database:

public int Auditproject (Project project)
{
SQL statements
String sql = "Update Project set Projectstatus=2,[email protected],[email protected],[email protected] where [email Protec Ted] ";
Organizational parameters


sqlparameter[] Objparams = new Sqlparameter[4];
Objparams[0] = new SqlParameter ("@ContractNO", Project.  CONTRACTNO); Contract number
OBJPARAMS[1] = new SqlParameter ("@ContractAmount", Project. Contractamount); Contract Amount
objparams[2] = new SqlParameter ("@ContractPhoto", Project.   Contractphoto); Contract Photos
OBJPARAMS[3] = new SqlParameter ("@ProjectID", Project.   ProjectID); Project number


Return Sqlhelper.executenonquery (sqlhelper.connstring, CommandType.Text, SQL, objparams);
}

Here is the use of my project part of the code user show, you can learn from the method to achieve specific functions. The main addition of a parameter class, passed through the parameters, and finally through the Cammand class implementation (because the SqlHelper class has been encapsulated, there is no concrete implementation).

2. The following is a picture of the database displayed in the ASP. first we need to consider what controls to display and note the properties of the control. The image is generally displayed using the Image Server Control , and the question is how to display it. Because the image control uses the ImageURL property of the image to assign a picture path value display, we store the picture as a binary byte stream to store the picture instead of the path to the picture. We can only transform it through other forms. Specific implementation: in our page to add a contractphoto.aspx (name can be casually written), this page mainly implements the function is not used to display the picture, the main use of response a read binary byte stream method, It then displays the picture in the form of the image control. specific practices:<asp:image id= "Imgcontractphoto" runat= "Server" height= "360px" width= "721px"/>

This is written in the server daemon code:

Imgcontractphoto.imageurl = "Contractphoto.aspx?" Projectid= "+ Project. ProjectID; Image

Used to point to a picture page and pass the appropriate parameters for a control to display different pictures under different conditions.

Here is the implementation of the Contractphoto.aspx backend code:

 protected void Page_Load (object sender, EventArgs e)
        {
           //define ProjectID get ProjectID in QueryString
        & nbsp   int projectid = Convert.ToInt32 (request.querystring["ProjectID"]);
           //Get project information through ProjectID
            PROJEC T project = Projectmanager.getprojectbyprojectid (ProjectID);
            byte[] b_contractphotoimg =project. Contractphoto;
            if (b_contractphotoimg.length > 0)
   {
response.c Lear ();
Response.ContentType = "Image/jpeg";
               response.outputstream.write (b_contractphotoimg, 0, B_ Contractphotoimg.length);
Response.End ();
   }
       }

Because data is taken out of the data to project. The process of Contractphoto was omitted, and a short code was posted to show the process of taking the byte stream.

Project.    Contractphoto = (byte[]) (reader["Contractphoto"]); Contract Picture

Reader is a SqlDataAdapter object.

This allows you to display the byte stream data stored in the database.

3. There is also a very important issue that needs to be explained: we all think that as long as our program is published to IIS can be implemented, it is true that publishing Web pages on the local IIS, the implementation of the functionality is not a problem, but published to the remote server will prompt the file does not have permissions or the file address does not exist problems. This problem has been tangled for a long time and finally solved. There are two main causes of the problem: 1. Local files uploaded to the server, we use FileUpload upload, the file address will be displayed, but this address is our local file address, when we publish the Web page to IIS on the server, the servers can not find the local computer address, it will prompt the file does not exist problems. If local IIS is locally published locally, IIS can access the local path directly, without any problems. Problem, how to realize the function??? 2. we can "save the curve", directly saved, we can use the FileUpload SaveAs method to create a upload folder on the service, and then use the SaveAs method to store the local files in the upload folder. When we need to access the file, we use the Server.MapPath method to get the project location and locate the file in upload. You can use the File.delete (string path) method to delete a server-side file if you are finished using it. so it's a bit of an abstraction to stick a piece of code.

The code is as follows:

string Filefullpath=server.mappath ("~/upload") + "\ \" +filename;
This.fupContractPhoto.SaveAs (Filefullpath);
Convert a file to a data stream
FileStream fs = new FileStream (Filefullpath, FileMode.Open); File stream
Byte[] Imagebytes=new Byte[fs.  Length]; Set byte stream array size
BinaryReader br = new BinaryReader (FS); Read Byte object
Imagebytes = Br. Readbytes (Convert.ToInt32 (fs.  Length)); Reads a byte stream into an array of bytes

At this point all the function points are finished, we can according to their own project needs to draw one or two points. Because read the online talk of the mixed, so in this complete expression, hope to give everyone help!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

C # use FileUpload to upload pictures to SQL database to store with image type and display considerations using the Image control

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.