Picture and file upload and download

Source: Internet
Author: User
Tags file upload insert advantage
Upload | download This article briefly describes how to upload a picture or file to a server or to a database in ASP.net 2.0, and how to display and download it after it is saved. 1. Save pictures and files to server 1.1 Upload This example constructs a page that uploads files to the specified directory on the server. (1) Create a new ASP.net Web site and add Web.config configuration files. (2) In Solution Explorer, click the right mouse button on the site name and add a folder named images as the path to the uploaded file. (3) into the Default.aspx design mode, from the Standard tab of the Toolbox, drag a FileUpload control onto the page with the default ID of "FileUpload1". The control is responsible for selecting a file. (4) Drag a button to the page, the Text property is set to "upload", and the ID is set to Btnupload. After clicking the button, upload the file. (5) increase the Click event for the Upload button. (6) in the Click event, add the following code:    protected void Btnupload_click (object sender, EventArgs e)     {        /Whether the file is selected, if not checked, prompts and returns the         if ( Fileupload1.filename = "")         {             Response.Write (' <script language= ' JavaScript ' >alert (' Please select a file and then click the Upload button! ');</script> ");            return;        }        /* To prevent uploaded files with duplicate names, append the upload time to the filename          * Get new filename start      */         //Get upload filename, note that this gets the full path + filename         String strFileName = fileupload1.filename;        //Get the last "\" position          int NInDex = strfilename.lastindexof (' \ \ ');        //Get real filename          strFileName = strfilename.substring (nindex + 1);         //Get file suffix before "." Location         nindex = Strfilename.lastindexof ('. ');         //change "filename. suffix" to "filename + time. Suffix" (that plus sign indicates connection)          strFileName = strfilename.substring (0, nindex) + DateTime.Now.ToString ("YYYYMMDDHHMMSS") + Strfilename.substring (nindex);       /* Get new file name end */         //Map the uploaded file's virtual directory to the server absolute path         string strpath = Server.MapPath ("./images/" + strFileName);        //upload file          FileUpload1.PostedFile.SaveAs (strpath);} (7) run, select a file and upload it to see if it's uploaded to the images directory. If you do not select the file directly upload, see if there is a hint. 1.2 Use of files The purpose of uploading files is to use it, generally in the process of uploading files, we put the new file name into the database. When used, you can use the Super connection <a href= './images/new filename ' > display text </a>. Click on the hyperlink, if it is a picture, it will open directly; if it is a file, a dialog box pops up, prompting you to save it or open it directly. If you upload a picture and embed it in a fixed location on the page, you can use the tag or use the image control. 1.3 Advantages and disadvantages the advantage of saving files to the server is that it is simpler to use. The disadvantage is that if you want to delete a file, you must create a writable virtual directory on the images, or you can set the published virtual directory directly to writable. setting a virtual directory as writable has a serious security flaw because anyone can write this virtual directory and can't put an end to a malicious file written by someone with ulterior motives. Therefore, the generic server does not allow writable virtual directories to be created, so deleting files is limited. Delete Files You can use the FileInfo class, you can write your own code to delete the file, look at the absence of a writable virtual directory when the deletion is possible, and then create a writable virtual directory to try again. 2. Pictures and files saved to database In this example, we take pictures for example, and the file operation is similar. 2.1 Upload (1) in the Dbtemp database, create a table named Upfiles that holds the uploaded picture, as follows:
Field name Significance Data type Note
Fileid File ID Int Set as field growth, primary key
FileName Filename Varchar (50)
Filecontent Upload the contents of the file Image
(2) add a Web Form named Default2.aspx. (3) Enter the design mode of the page and drag into a fileupload. (4) drag into a button,text set to "upload" with the id "btnupload". (5) drag into a GridView to display the file name. (6) data Source Select New data source, and the new Data Source wizard pops up. GridView (7) The data source type is selected as "database", the name is Sqlfilesource, OK. (8) Create a new database connection, if you forget how to do, you can refer to the blog "asp.net2.0 Introduction (1)--access to the database" that article. (9) in the Configure SQL statement interface, select Specify custom SQL statements or stored procedures, and then select Next. (Ten) The statement is set to "select Fileid, FileName, filecontent from Upfiles order by Fileid". Select (one) The statement is set to INSERT into Upfiles (FileName, filecontent) VALUES (@FileName, @FileContent). Insert (a) The statement is set to "DELETE from Upfiles WHERE (Fileid = @original_FileID)". Delete (a) complete the creation of the data source and enable deletion. (a) Set the Sqlfilesource oldvaluesparameterformatstring property to "original_{0}". (a) Click the button after the InsertQuery property, select the parameter filecontent, set the parameter source to Control,controlid set to FileUpload1, OK. (a) after setting, the code in the body of ASPX is as follows:<body>    <form id= "Form1" runat= "Server" >    <div>         <asp:fileupload id= "FileUpload1" runat= "Server" width= "338px"/>         <asp:button id= "btnupload" runat= "server" text= "upload"/>         <asp:gridview id= "GridView1" runat= "Server" autogeneratecolumns= "False" datakeynames= "Fileid"             datasourceid= "Sqlfilesource" >             <Columns>                 <asp:commandfield showdeletebutton= "True"/>                 <asp:boundfield Datafield= "Fileid" headertext= "Fileid" insertvisible= "False" readonly= "True"                     sortexpression= "FileID"/>                 <asp:boundfield datafield= "filename" headertext= "filename" sortexpression= "filename"/>             </Columns>        </asp:GridView>         <asp:sqldatasource id= "Sqlfilesource" runat= "Server" connectionstring= "<%$ connectionstrings:dbtempconnectionstring%>"              deletecommand= "DELETE from Upfiles WHERE (Fileid = @original_FileID)" insertcommand= " INSERT into Upfiles (FileName, filecontent) VALUES (@FileName, @FileContent) "             oldvaluesparameterformatstring= "original_{0}" selectcommand= select Fileid, FileName, Filecontent From Upfiles-Fileid ">            < deleteparameters>                <asp:parameter name= "Original_fileid"/>            </DeleteParameters>            < insertparameters>                <asp:parameter name= "FileName"/>                 <asp:controlparameter controlid= "FileUpload1" name= "filecontent" propertyname= "Filebytes" >            </InsertParameters>         </asp:SqlDataSource>    </div>    </ Form></body> (a) increase the Click event for the upload button:    protected void Btnupload_click (object sender, EventArgs e)     {        /Whether the file is selected, if not checked, prompts and returns the         if ( Fileupload1.filename = "")         {             Response.Write (' <script language= ' JavaScript ' >alert (' Please select a file and then click the Upload button! ');</script> ");            return;        }        //Get upload filename, note that this gets the full path + filename         String strFileName = fileupload1.filename;         //Get the last "\" position         int nindex = Strfilename.lastindexof (' \ \ ');        //Get real filename          strFileName = StrfilenamE.substring (nindex + 1);        //Insert Data          sqlfilesource.insertparameters["FileName"]. DefaultValue = strfilename;        Sqlfilesource.insert ();} (km) Run the program, select a picture upload, you can see the display in the list. Delete a picture and you can see that it can be deleted directly. 2.2 Display of pictures after the picture is put in the database, there are some problems, because we have no way to request it directly with attributes such as SRC or ImageUrl. But when we look at the article in the blog Web Drawing (1)-server-side drawing, we can find a way to take the picture out and save it with an ASPX page and convert the ASPX page into picture data. now we're going to display the file name in that GridView column. Do a hyperlink, click on the hyperlink to display the picture, the process is as follows: (1) Right-click the site name of the Solution Explorer, select App_Code under the Add ASP.net folder menu, and create an App_Code folder. We write code that is not in the ASPX page, and the dataset you create must be placed under this folder (Microsoft sometimes makes a fool of itself for its own convenience), we will create a typed dataset under this folder to read the contents of the file. (2) on the new App_Code folder, right-click and select the Add New Item menu. (3) Pop-up dialog box, select "DataSet", named "Fileset.xsd", select the "Add" button, this time pop-up "TableAdapter Configuration Wizard." (You can put multiple tables in one dataset, you can drag a TableAdapter from the Toolbox when you add the second table, and the rest is the same as the following method). (4) The first step in the wizard is to establish the connection string, because we have already built one before, we don't need to create a new, just select that. (5) The next step is to select the command type, and we choose "Use SQL statements" and then next. (6) The statement input "Select Fileid, FileName, filecontent from Upfiles WHERE (Fileid = @FileID)". SQL (7) The next step is to complete, so set up a dataset, and we can also see that there is a upfiles table, corresponding to the table in the database. Under the table, there is a upfilestableadapter, which automatically generates the fill code to read data from the database, as well as the update code for the database (Microsoft is very thoughtful, all the code is written for us). (8) Create a Web form called "imageshow.aspx", where we'll read the data in the database and save it as a picture. (9) In the Page_Load event for the form, enter the following code:    protected void Page_Load (object sender, EventArgs e)     {        //Create DataSet instance         fileset Fileset = new Fileset ();   & nbsp;     //Create data adapter instance         Filesettableadapters.upfilestableadapter adapter = new Filesettableadapters.upfilestableadapter ();         //Read data, we passed the parameter Fileid from the GridView via QueryString, which is the file recorded in the database id         adapter. Fill (fileset.upfiles, Int. Parse (request["Fileid"));        //Take out the contents of the binary file, assuming that the file must exist, The Filecontent field on line No. 0 is the data we want to take         byte[] by = (Byte []) fileset.upfiles.rows[0][ "Filecontent"];        //write output stream          Response.BinaryWrite (by);} (Ten) back to the default2.aspx design pattern, we are showing the filename in the front GridView, and the following is a hyperlink display. (one) With the GridView selected, click the button behind the Columns property to eject the displayed Field dialog box. (a) deletes the filename field in the Selected Fields list box. (a) in the Available Fields list box, select Hypelinkfield to add to the Selected Fields list box. (a) Select the new "Hypelinkfield" and modify the following properties:
Property name Value Comments
DataNavigateUrlFields Fileid Bound URL Field
Datanavigateurlformatstring Imageshow.aspx? FILEID={0} URL format, passing Fileid parameters to imageshow.aspx
DataTextField FileName Fields that are displayed
HeaderText File name GridView Header for this column
Target _blank Click Hyperlink to pop up a new window to display the picture
(a) OK after the run, look at the effect. The hyperlink column shows the file name, and clicking on the hyperlink will pop up a new window (you don't have to get your firewall to intercept it), and the new window shows the pictures we uploaded. 2.3 Advantages and disadvantages The advantage is more obvious, is to delete easier, delete that record on it, there is no writable virtual directory security worries. shortcomings are also more obvious, is trouble. 3. About file Bulk upload There are a lot of people asking or trying to find a way to achieve a large number of files upload, that is, to upload a batch of files, rather than one choice. If you really understand the Internet, you won't have that idea anymore. Imagine if there was a browser that could upload a lot of files, can write a website, as long as others browse your website, you can put other people's hard disk files read into your server up, all the other people's secrets are exposed to your eyes, this is an unforgivable security problem. in fact, browsers want to achieve a lot of file upload, technically not difficult, but this browser certainly no market, no one dares to use it. ActiveX is easy to implement this feature, which is one of the reasons why ActiveX security is widely criticized. Forget the file bulk upload, the Web program can only select a file, upload one. To upload n files at the same time, you need to place n fileupload on the page.

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.