Home>

This article mainly introduces uploading files in asp.net for demonstration,We built two fields on the database,Store binary images and pdf paths separately, and then explain how to use fileupload to complete uploading files.

preface:

So far,Our tutorial revolves around text data. However, many applications need to handle both text and binary data.For example, a recruitment site may require users to upload a resume in word or pdf format.

Using binary data faces a challenge:how to store binary data in the application.We must update the interface for adding records to allow users to upload files from their local computer,And add additional features to download the relevant binary data of a record.In this chapter and the next three chapters, we explore how to deal with these issues.At the end of this series of tutorials,We will create a fully functional application,It provides relevant pictures and pdf brochures for each type of record. In this series of tutorials,We explore various methods of storing binary data,Investigate how to allow users to upload files from their own computers and store them in the server's file system.

Note:Binary data is sometimes called "blob" (short for binary large object). I chose to use the term "binary data" for this tutorial, even though it agrees with the term blob.

Step 1:Add a working with binary data tutorial page

Let's take a moment to create some pages on the website,These pages will be used in this tutorial.First add a folder named binarydata,Then add the following page.Make sure that site.master is selected as the master page for each page.

default.aspx

fileupload.aspx

displayordownloaddata.aspx

uploadindetailsview.aspx

updatinganddeleting.aspx

Figure 1:Add the required pages

Like other folders,The default.aspx in the binarydata folder is used to list the tutorial chapters.Remember that the sectionleveltutoriallisting.ascx user control provides this functionality.So, drag this user control onto the page from the solution browse.

Figure 2:Add sectionleveltutoriallisting.ascx user control to default.aspx

Finally, add the addresses of these pages to the web.sitemap entry.Add the following markup after enhancing the gridview<sitemapnode> ;.

<sitemapnode
 url="~/binarydata/default.aspx"
 description="extend the data model to include collecting binary data.">
 <sitemapnode
 url="~/binarydata/fileupload.aspx"
 description="examine the different ways to store binary data on the
 web server and see how to accept uploaded files from users
 with the fileupload control. "/>
 <sitemapnode
 url="~/binarydata/displayordownloaddata.aspx"
 description="let users view or download the captured binary data." />
 <sitemapnode
 url="~/binarydata/uploadindetailsview.aspx"
 description="learn how to augment the inserting interface to
 include a fileupload control. "/>
 <sitemapnode
 url="~/binarydata/updatinganddeleting.aspx"
 description="learn how to update and delete existing binary data." />
</sitemapnode>

After modifying the web.sitemap, take a look at this tutorial site in your browser.

Figure 3:The site map contains this tutorial

Step 2:Where to Store Binary Data

There are two ways to store binary data:one is to store it in the file system of the server,And store the file path in the database;The second is to store it directly in the database (see Figure 4). Both methods have their advantages and disadvantages.

Figure 4:Binary data can be stored on the file system or directly in the database

Suppose we extend the database northwind,Each product corresponds to a picture.One way is to store these pictures in the server file system,Then record the file path of the picture in the products table.To this end, we are going to

Add a column to the products table,Named imagepath and type is varchar (200). Suppose when a user uploads an image for the product chai,Pictures may be stored in ~/images/tea.jpg on the server file system. Here, ~ represents the physical location of the application.That is,If the site is rooted at c:/websites/northwind /, ~/images/tea.jpg is equivalent to c:/websites/northwind/images/tea.jpg. After uploading the image,We should update the record chai in the products table so that its imagepath column refers to the path of the image.If we decide to put pictures of all products in the images folder of the application, we can use "~/images/tea.jpg" or "tea.jpg" to represent.

The main advantages of placing binary data on the file system are:

1. Easy to execute-as we will see soon,Compared to placing binary data directly in the database and storing it in the file system,When users need to store and retrieve data they need more code.In addition, for users to view or download data,You must use a url to locate the data. If data is stored in the file system,url is intuitive and clear;If it is stored in a database,You must create a page to get and return data.

2. Wide access range-other services or programs sometimes need to access binary data,But when binary data is stored in the database,These services or programs are no longer accessible.For example, users may want to access the pictures corresponding to each product through ftp.under these circumstances,It is best to place it on the file system.

3. Better execution performance-placing binary data in the file system compared to a database,There are fewer queries and network congestion between the database service and the server service.

The main disadvantage of placing binary data in the file system is that it weakens the relevance of the data.For example, when we delete a record from the table products,Related files placed in the file system are not automatically deleted,So we have to write the code to delete it.otherwise,As file fragments slowly accumulate,The file system can become messy.In addition, any changes to the database,Make changes to the corresponding binary data in the file system.This is the case when moving databases to another site or server, for example.

As a choice,You can create a column of type varbinary in Microsoft SQL Server 2005 to store binary data.You can specify the maximum length of the stored data,For example, i want the maximum length of the data to not exceed 5000 bytes, and the specified type is varbinary (5000);and varbinary (max) is the maximum storage space that Microsoft SQL Server 2005 can provide.Approximately 2 gb.

of The main advantage of storing binary data in a database is that it associates database records with binary data.It greatly simplifies database management,Such as transferring the database to another website or server.Similarly, when deleting a record,At the same time, the relevant binary data is automatically deleted.

Note:In Microsoft SQL Server 2000 and earlier versions,The varbinary type supports a maximum of 8000 bytes. To support 2gb binary data,It is necessary to use the image type. After the introduction of max in sql server 2005, the image type has begun to fade.Despite backward compatibility,Microsoft announced that it will discard the image type in subsequent versions of SQL Server.

If you are using an older data type,You may have seen the image type. The table categories in the database northwind has a picture column that can be used to store binary image files of a certain class.Because the database northwind originated from Microsoft Access and earlier versions of SQL Server,So the type of picture column is image.

In this chapter and the next 3 chapters, we will use both methods.The table categories already has a column picture to store the binary picture files of the class,We also need an additional column, path, to store the path to the pdf in the file system.

Step 3:Add brochurepath column to table categories

At present, the category category contains only 4 columns:categoryid, categoryname, description, and picture. In addition,We also need to add a column,Point to a booklet of that type, if it exists. Open Server Explorer,Click on the table node,Right-click on the table categories and select "Open Table Definition" (see Figure 5). If you don't see Server Explorer,Select it in the view menu,Or press ctrl + alt + s.

Add to In the table categories, add a column named brochurepath, the type is varchar (200), and its value is allowed to be null. Click the save button (or press ctrl + s).

Figure 5:columnpath added to table categories

Step 4:Update the architecture to use picture and brochurepath columns

Currently, the categories datatable in the data access layer defines four datacolumns:categoryid, categoryname, description, and numberofproducts. We originally started in the tutorial "Create a data access layer"When creating categoriesdatatable, it only contains the first 3 columns, and the numberofproducts column is in Chapter 35"Implement master/slave report with repeater and datalist single pageCreated here.

Like in the textbook "Create a data access layerAs discussed indatatables form business objects in the form of type datasets.The role of tableadapters is to connect to the database,And composed of query results

Business objects.categoriesdatatable is composed of categoriestableadapter, which contains three data access methods:

Getcategories ():execute the main query of this tableadapter,Returns the record's categoryid, categoryname, and description. The automatically generated insert and update methods are mainly used by this method.

Getcategorybycategoryid (categoryid):It also returns the categoryid, categoryname, and description of the record, provided that the categoryid value matches.

Getcategoriesandnumberofproducts ():It also returns the categoryid, categoryname, and description of the record, and returns the number of products in each category.

We have noticed,These methods do not return the picture or brochurepath of the categories;the columns are not shown in the categoriesdatatable.In order to be able to use picture and brochurepath, we need to add them to categoriesdatatable first,Then update the categoriestableadapter to return their values.

Add picture and brochurepath columns

First add them to categoriesdatatable. Right click on the top of categoriesdatatable,Select "Add" from the menu and select the "Columns" option. This will create a data column named data1 for datatable (datacolumn) and rename it to picture. Set its datatype property to "system.byte []" in the properties window (it should not be selected in the drop-down list,It needs to be entered manually)

Figure 6:Create a data column named picture,Let the data type be system.byte []

Add another column named brochurepath,Use the default data type (system.string)

Return values ​​picture and brochurepath from tableadapter

Add to After adding the above 2 columns to the categoriesdatatable, we are ready to update the categoriestableadapter. We can return these 2 values ​​in the main query of the tableadapter, but every time we call getcategories () it returns binary data.How could it be?We can make the main query return the brochurepath value, and create another method to return a particular kind of picture value.

Update In order to update the main query,Right-click on the top of the categoriestableadapter,Select the "Configuration" item, this will launch the table adapter setup wizard,Update the query to return to the path, and click Finish.

Figure 7:Update the select command to return the route

When using ad-hoc sql statement to update the main query in tableadapter,It will update the columns involved in the query of all methods in the tableadapter.That is, update the getcategorybycategoryid (categoryid) method to return the brochurepath value;update the getcategoriesandnumberofproducts () method and delete the query that returns several products per category (that is, delete numberofproducts). Therefore, we right-click getcategoriesandnumberofproducts () and select "Configuration" to restore it to the original query:

select categoryid, categoryname, description, (select count (*)
 from products p
 where p.categoryid=c.categoryid)
 as numberofproducts
from categories c

Then, create a tableadapter method that returns a particular kind of picture value. Right-click on the top of the categoriestableadapter,Select "Add Query". This will open the tableadapter query setup wizard.First choose how to access the database,There are three ways:using SQL statements, creating a new stored procedure, or using an existing stored procedure.We choose "Use sql statement", click next step,Select "select (return line) (s)" in the interface.

Figure 8:Choose to use SQL statement

Figure 9:Since the query returns a record,We choose "Select Row".

Click Next.Type the following SQL query and click next:

select categoryid, categoryname, description, brochurepath, picture
from categories
where [email protected]

Finally, name the new method.The method for filling the datatable is named fillcategorywithbinarydatabycategoryid;the method for returning the datatable is named getcategorywithbinarydatabycategoryid. Click finish to complete the setup.

Figure 10:Name the tableadapter method

Note:After setting up,We will see a dialog box,Prompts you "The schema of the data returned by the new command text is different from that of the main query.If this is not expected,Please check the command text of the query.".in short,The wizard realized that the main query—getcategories () — is different from the data returned by the method we just created.This is exactly what we want,Just ignore it.

At the same time, keep in mind that if you choose ad-hoc sql statements in the wizard, and then change the main query of tableadapter,It will change the columns involved in the select command in the getcategorywithbinarydatabycategoryid method,To include those columns used by the main query (that is, remove the picture column from the query). We have to update the code manually,Make it return picture, similar to how we handled the getcategoriesandnumberofproducts () method earlier.

When finished adding 2 data columns in the categoriesdatatable,After adding the getcategorywithbinarydatabycategoryid method to the categoriestableadapter, these classes should look similar to Figure 11 in the dataset designer.

Figure 11:dataset designer contains new columns and new methods

Update business logic layer (bll)

After updating the data access layer,The next step is to extend the business logic layer to cope with the newly added categoriestableadapter method. Add the following code to the categoriestableadapter:

[system.componentmodel.dataobjectmethodattribute
 (system.componentmodel.dataobjectmethodtype.select, false)]
public northwind.categoriesdatatable
 getcategorywithbinarydatabycategoryid (int categoryid)
{
 return adapter.getcategorywithbinarydatabycategoryid (categoryid);
}

Step 5:Upload a file from the client to the server

usually,The user uploads a file on the local computer to the server,This involves the form in which the data is processed,Is it stored directly in the database?Still store it in the file system,Then store its file path in the database?Here we explore how to upload files to the server,In the following tutorial we will focus on the data pattern of uploaded files.

Asp.net 2.0 newly added fileupload web control provides a mechanism,For users to upload files.It is aelement with a type attribute of "file". It looks like a text box with a browse button in the browser.After clicking the browse button, a dialog box pops up for the user to select a file.After being selected and returned, the contents of the selected file are delivered to the server together.On the server side,We can get the information of the uploaded file through the properties of the fileupload control.

Upload files for verification,Open the fileupload.aspx page of the binarydata folder and switch to design mode.Drag a fileupload control from the toolbox to the page,Let its id be uploadtest. Add another button control, set its id to uploadbutton, and its text property to "upload selected file". Finally, add a label control under the button control, set its id to uploaddetails and clear the text property.

Figure 12:Add a fileupload control to the asp.net page

Figure 13 shows how the page is viewed in a browser.We have noticed,When you click the browse button, a dialog box pops up,Allows the user to select a file to upload.When a file is selected,When you click the "upload selected file" button again, the page returns,Pass the binary data of the file to the server.

Figure 13:File selected by user for upload to server

After the page returns,Uploaded files can be stored in the file system,It can also be called in the form of a "stream".In this example, we store it in the folder ~/brochures. First create a brochures folder in the root directory, and then create an event handler for the click event of the uploadbutton:

protected void uploadbutton_click (object sender, eventargs e)
{
 if (uploadtest.hasfile == false)
 {
 //no file uploaded!
 uploaddetails.text="please first select a file to upload ...";
 }
 else
 {
 //display the uploaded file "s details
 uploaddetails.text=string.format (
 @ "uploaded file:{0}<br />
 file size (in bytes):{1:n0}<br />
 content-type:{2} ", uploadtest.filename, uploadtest.filebytes.length, uploadtest.postedfile.contenttype);
 //save the file
 string filepath =
 server.mappath ("~/brochures /" + uploadtest.filename);
 uploadtest.saveas (filepath);
 }
}

The fileupload control provides a variety of properties for processing uploaded data.For example, the hasfile attribute indicates whether the user uploaded a file;The filebytes property accesses data in bytes.The click event handler determines in advance whether to upload a file,If so, the label control lists the file name, byte size, and type.

Note:To ensure users upload files,You can use the requiredfieldvalidator control or check the hasfile property. If it is false, a warning message is raised.

The saveas (filepath) attribute of the fileupload control stores the file at a specified filepath. The path must be a physical path (such as c:/websites/brochures/somefile.pdf), not a relative path (such as:/brochures/somefile.pdf). The method server.mappath (virtpath) intercepts a relative pathThe physical path is returned.Here, the relative path is ~/brochures/filename, where filename is the name of the uploaded file.

After the click event handler is completed,Take a few minutes to view the page in your browser,Click the browse button to select a file from your hard drive for upload.Click the "upload selected file" button again,Upload the file to the ~/brochures folder.After uploading the file,Return to visual studio, click the "Refresh" button in the solution explorer, and you will see the newly uploaded file in the ~/brochures folder.

Figure 14:The file has been uploaded to the server

Figure 15:Uploaded files are saved in ~/brochures folder

Save uploaded files in the file system

When saving uploaded files to the file system,There are a few points to note.The first is security.To save files to the file system,The running page must have write permission.If you use microsoft "s internet information services (iis) as the server,Its security depends on the version and settings of iis.

Another challenge is the naming of uploaded files.Generally speaking,When pages save files in the ~/brochures folder,Use its original name directly on the user's computer.For example, user a uploads a file named brochure.pdf and saves it as ~/brochure/brochure.pdf after uploading. If user b also uploads the file laterAnd the name also happens to be brochure.pdf, what happens?As far as our current code is concerned,User b's file will overwrite user a's file.

There are several ways to handle naming conflicts.One is when storing files with the same name,Block file upload.For example, when user b tries to upload a file named brochure.pdf,Prompt it to rename and try again.Another method is to use a uniquely identified file name,It can be a globally unique identifier (guid), or the primary key value of the corresponding database record.We will explore this in detail in the next tutorial.

Problems facing large volumes of binary data

The tutorial assumes that the processed binary data is moderately sized.When dealing with large amounts of binary data—such as a few mb or even larger,It's beyond the scope of this tutorial.by default, asp.net processes up to 4mb of data, although you can set the maximum value that can be processed in theelement of the web.config file,But iis also limits the size of uploaded files.See article "iis upload file size".

In addition, the time it takes to upload a large amount of data files is likely to exceed the 110 seconds that ASP.NET waits by default, and it also faces the memory and execution efficiency issues of processing large data.

The fileupload control is not suitable for uploading large files.When uploading large files,Users need to wait patiently,It ’s not possible to determine if the upload is in progress.There is no problem uploading small files.Maybe just a few secondsLarge files can take several minutes.There are many third-party file upload controls that are more suitable for uploading large files and provide progress tips.Provide a better user experience.

If your application needs to handle large files,You have to seriously consider the challenges you face,Find the solution that works for you.

to sum up:

Creating an application that handles binary data faces some problems.This tutorial explores two of these issues:how to store data and allow users to upload files through a page.In the next tutorial we explore how to deal with binary data in database records,And how to display it.

Happy programming!

About the Author

  • Previous jQuery countdown effect based on extension
  • Next thinkPHP simple traversal array method analysis