Operating data in ASP.net 2.0 52: Using FileUpload Upload file _ self-study process

Source: Internet
Author: User
Tags extend microsoft sql server microsoft sql server 2005 table definition

Introduction:

So far, our tutorial revolves around the text data. However, many applications need to process both text data and binary data. For example, a recruiting website may require users to upload resumes in Word or PDF format.

Using binary data is a challenge: how to store binary data in your application. We must update the interface to add records to enable users to upload files from the local computer and add additional functionality to download the relevant binary data for a record. In this chapter and the next 3 chapters, we explore how to deal with these issues. At the end of this series, we'll create a full-featured application that provides relevant pictures and PDF brochures for each type of record. In this series of tutorials, we explore various ways to store binary data, examining 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 referred to as "BLOB" (Binary Large object abbreviation). This tutorial I chose to use the term "binary data" even though it and the term blob agree.

1th Step: Add working with Binary Data tutorial page

Let's take a moment to create some pages on the site that will be used in this tutorial. First, add a folder named BinaryData, and then add the following page. Make sure that each page is selected with Site.master as the master sheet.

Default.aspx
Fileupload.aspx
Displayordownloaddata.aspx
Uploadindetailsview.aspx
Updatinganddeleting.aspx


Figure 1: Adding the required pages

Like other folders, the Default.aspx in the BinaryData folder is used to list the tutorial chapters. Remember Sectionleveltutoriallisting.ascx This user control provides this functionality. Drag the user control onto the page from solution browsing.


Figure 2: Adding Sectionleveltutoriallisting.ascx user controls to Default.aspx

Finally, add the addresses of these pages to the Web.sitemap entry. After enhancing the GridView <siteMapNode> adds the following tag.

<sitemapnode title= "Working with Binary data" url= "~/binarydata/default.aspx" description= "the data model to Include collecting binary data. " > <sitemapnode title= "uploading Files url=" ~/binarydata/fileupload.aspx "description=" examine the different W  Ays to store binary data on the Web server and I-accept uploaded files from users with the FileUpload control. " /> <sitemapnode title= "Display or Download Binary Data" url= "~/binarydata/displayordownloaddata.aspx" Descripti On= "Let users view or download the captured binary data."/> <sitemapnode title= "adding New binary Data" url= "~/b Inarydata/uploadindetailsview.aspx "description=" Learn to augment the inserting interface to include a FileUpload co Ntrol. "/> <sitemapnode title=" Updating and deleting Existing Binary Data "Url=" ~/binarydata/updatinganddeleting. aspx "description=" Learn how to update and delete existing binary data. "/> </siteMapNode>

After modifying the Web.sitemap, look at this tutorial site in the browser.


Figure 3:site Map contains this tutorial

Step 2nd: Store binary data somewhere

There are 2 ways to store binary data: One is to store it in the server's file system and store the file path in the database, and the second is to store it directly in the database (see Figure 4). Each of the 2 methods has its own advantages and disadvantages.


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

Let's say we extend the database Northwind and each product corresponds to a picture. One way to do this is to store the pictures in the server file system and then record the file path for the picture in the table products. To this end, we are going to
The Products table adds a column named ImagePath, and the type is varchar (200). If the user uploads a picture for the product chai, the picture may be stored in the ~/images/tea.jpg location of the server file system. Here, ~ Represents the physical location of the application. In other words, if the site is rooted in c:/websites/northwind/, ~/images/tea.jpg is equivalent to c:/websites/northwind/images/tea.jpg. After uploading the picture, we should update the record chai in the table products so that its ImagePath column refers to the path of the picture. 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 them.

The main advantages of placing binary data in a file system are:

1. Ease of implementation-as we will see, the binary data is placed directly in the database and stored in the file system, requiring more code when the user needs to store and retrieve the data. In addition, to view or download data for the user, you must use the URL to locate the data (the Uniform Resource Locator). If the data is stored in a file system, the URL is straightforward, and if it is stored in a database, you must create a page to fetch and return the data.

2. Wide access-other services or programs sometimes need access to binary data, but when binary data is stored in the database, the services or programs are inaccessible. For example, a user might want to use FTP to access a picture of each product, in which case it is best to place it in the file system.

3. Better performance-the query and network congestion between the database service and the Server service is less in comparison to the file system and database than the binary data.

The main disadvantage of placing binary data in a file system is the weakening of data correlation. For example, when we delete a record from the table products, the related files placed in the file system are not automatically deleted, so we must delete them by hand-written code. Otherwise, as the file fragments accumulate, the file system becomes cluttered. In addition, any changes to the database should be made to the corresponding binary data in the file system to make changes. This is the challenge, for example, when transferring a database to another site or server.

As a choice, you can create a varbinary-type column in Microsoft SQL Server 2005 to store binary data. You can specify the maximum length of the stored data, such as you want the maximum length of the data to not exceed 5000 bytes, the specified type is varbinary (5000); varbinary (max) is the largest storage space available for Microsoft SQL Server 2005, about 2 GB.

The primary advantage of storing binary data in a database is that it associates database records with binary data. It greatly simplifies the management of the database, such as moving the database to another Web site or server. Similarly, when a record is deleted, the associated binary data is automatically deleted.

Note: In Microsoft SQL Server 2000 and earlier versions, the varbinary type has a maximum support of 8000 bytes, and to support 2GB binary data, use the image type. After the introduction of Max in SQL Server 2005, the image type has already begun to fade. Despite backwards compatibility, Microsoft claims to discard the image type in subsequent versions of SQL Server.

If you are using an earlier 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 a binary image file for a class. Because database Northwind originated in Microsoft Access and earlier versions of SQL Server, the picture column is of type image.

This chapter and the next 3 chapters, we have 2 methods to use. Table categories already has a list of pictures to store the binary picture files of the class, and we want an extra column brochurepath to store the path to the PDF in the filesystem.

3rd Step: Add brochurepath column for table categories

Currently, the table categories contains only 4 columns: CategoryID, CategoryName, description, and picture. In addition, we need to add a column that points to the brochure (if any) of the class. Open Server Explorer, click the Table node, right-click 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 a column named Brochurepath in the table categories, with a type of varchar (200), allowing null values. Click the Save button (or press ctrl+s).


Figure 5: Columns added Brochurepath in table categories

Step 4th: Update the architecture to use the picture and Brochurepath columns

Currently, the categoriesdatatable in the data Access Layer (Layer) defines 4 Datacolumns:categoryid, CategoryName, Description and Numberofproducts. When we first created the categoriesdatatable in the tutorial "Creating a data access layer", it contained only the first 3 columns, and the Numberofproducts column was in the 35th chapter Created in master/from report using Repeater and DataList single pages.

As discussed in the textbook, "Creating a data access layer," DataTables a business object in the form of a type dataset. The role of TableAdapters is to connect to the database and make the query results
Business object. Categoriesdatatable is composed of Categoriestableadapter, which contains three methods of data access:

GetCategories (): Performs the main query of the TableAdapter, returns the records of the CategoryID, CategoryName and description these 3 items. The automatic generation of insert and update methods is primarily the method used.

Getcategorybycategoryid (CategoryID): is also the return record of the CategoryID, CategoryName and description These 3 items, if the CategoryID value to match.

Getcategoriesandnumberofproducts (): Also returns the records of the CategoryID, CategoryName and description of these 3 items, while returning the number of products per category.

We note that these methods do not return the table categories in the picture or brochurepath;categoriesdatatable and do not show these columns. In order to be able to use the picture and brochurepath, we need to add them first in the categoriesdatatable and then update the class Categoriestableadapter to return their values.

Add picture and Brochurepath columns

First add them to the categoriesdatatable. Right-click the top of the categoriesdatatable, select Add from the menu, and then select the Columns option. This creates a data column (DataColumn) named Column1 for the DataTable and renames it to the picture. Set its DataType property to ' system.byte[' in the Properties window (not available in the Drop-down list, so it needs to be entered manually)


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

Add another data column named Brochurepath, using the default data type (System.String)

Return value from TableAdapter picture and Brochurepath

After adding the above 2 columns in categoriesdatatable, we are ready to update categoriestableadapter. We can return these 2 values in the TableAdapter main query, but each call to GetCategories () returns the binary data. What's the good of it? We can have the main query return the Brochurepath value and create a different method to return a particular kind of picture value.

To update the main query, right-click on the top of the Categoriestableadapter, select the "Configuration" entry, which will start the Table Adapter Setup Wizard, update the query to return Brochurepath, and click Finish.


Figure 7: Updating the Select command, returning Brochurepath

When you update the main query in TableAdapter using the AD-HOC SQL statement, it updates the columns that are involved in the query for all methods in TableAdapter. In other words, update the Getcategorybycategoryid (CategoryID) method to return the Brochurepath value, and update the Getcategoriesandnumberofproducts () method. and delete the query that returns several products for each category (also delete numberofproducts) Therefore, we right-click on Getcategoriesandnumberofproducts () and select "Configure" to revert to the original query statement:

Select CategoryID, CategoryName, Description,
 (select COUNT (*) from the 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 at the top of categoriestableadapter and select Add Query, which will open the TableAdapter Query Setup Wizard. There are 3 ways to first choose how to access a database: Using SQL statements, creating a new stored procedure, and using an existing stored procedure. We chose "Use SQL statements", click Next, select "Select (Return rows)" (S) in the interface.


Figure 8: Choosing to use SQL statements


Figure 9: Because the query returns a record, we choose Select Row.

Click Next, type the following SQL query, click Next:

SELECT CategoryID, CategoryName, Description, Brochurepath, picture from
Categories
WHERE CategoryID = @ CategoryID

Finally, name the new method. The method for populating the DataTable is named Fillcategorywithbinarydatabycategoryid ; A method that returns a DataTable is named Getcategorywithbinarydatabycategoryid. Click Finish to complete the setup.


Figure 10: Naming the TableAdapter method

  Note: When you have finished setting up, we will see a dialog box that prompts you that the schema of the data returned by the new command text is different from the structure of the main query. If you do not expect this to happen, check the command text for your query. ”。 In short, the wizard realizes that the main query-getcategories () is different from the data returned by the method we just created. This is exactly what we want to do, and ignore it.

Also, keep in mind that if you select the Ad-hoc SQL statement in the wizard and then change the TableAdapter main query, it will change the columns that are involved in the Select command in the Getcategorywithbinarydatabycategoryid method. To include those columns that are used by the main query (that is, to remove the picture column from the query). We have to manually update the code so that it returns to the picture, similar to the way we dealt with the Getcategoriesandnumberofproducts () method earlier.

When you finish adding 2 data columns to the categoriesdatatable and adding Getcategorywithbinarydatabycategoryid methods to Categoriestableadapter, These classes 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 respond to the newly added Categoriestableadapter method, adding the following code to the class Categoriestableadapter:

[System.ComponentModel.DataObjectMethodAttribute
 (System.ComponentModel.DataObjectMethodType.Select, false)]
Public northwind.categoriesdatatable
 Getcategorywithbinarydatabycategoryid (int categoryid)
{
 return Adapter.getcategorywithbinarydatabycategoryid (CategoryID);
}

5th step: Upload a file from the client to the server

Typically, a user uploads a file on the local computer to the server, which involves the form of processing the data and storing it directly in the database? or store it in a file system, and then store its file path in the database? Here we explore how to upload files to the server, and in the following tutorial we focus on uploading data patterns to files.

ASP.net 2.0 The newly added FileUpload Web controls provide a mechanism for users to upload files. It is a <input> component with a type attribute of "file". It looks like a text box with a browse button in the browser. When you click the Browse button, a dialog box pops up for the user to select the file. selected, sent back, the contents of the selected file are passed together to the server. On the server side, we can get information about the uploaded file by fileupload the properties of the control.

To verify the upload file, open the BinaryData folder's fileupload.aspx page and switch to design mode. Drag a FileUpload control from the toolbox to the page and set its ID to uploadtest. Add a button control with its ID Uploadbutton,text property to "Upload Selected File". Finally, add a Label control under the button control, set its ID to uploaddetails and empty the Text property.


Figure 12: Adding a FileUpload control on the asp.net page

Figure 13, to see the page in the browser, we notice that when you click the Browse button, a dialog box pops up for the user to select the file to upload. When a file is selected and the "Upload Selected File" button is clicked, the page is returned and the binary data of the file is uploaded to the server.


Figure 13: The user chooses to upload the file to the server

After the page is returned, the uploaded file can be stored in the file system and can be invoked in the form of "stream". In this case, we store it in a folder ~/brochures. First create an brochures folder in the root directory, and then create an event handler for the Uploadbutton click event:

protected void Uploadbutton_click (object sender, EventArgs e)
{
 if (Uploadtest.hasfile = False)
 {
 // No file uploaded!
 Uploaddetails.text = "Please 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}" C14/>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 handling uploaded data. For example, the HasFile property indicates whether the user uploaded the file; The Filebytes property accesses the data in bytes. Click the event handler to determine whether the file is uploaded beforehand, and if so, the Label control lists the file name, byte size, and type.
Note: To ensure that the user uploads the file, you can use the RequiredFieldValidator control or check the HasFile property, and if it is false, give a warning message.

The SaveAs (FilePath) property of the FileUpload control stores the file in a specified file path (filePath). The path must be a physical path (such as c:/websites/brochures/somefile.pdf) rather than a relative path (such as:/brochures/somefile.pdf). Method Server.MapPath (Virtpath) intercepts the relative path and returns the physical path. Here, the relative path is ~/brochures/filename, and its filename is the name of the uploaded file.

After completing the Click event handler, take a few minutes to view the page in the browser, click the Browse button, and select a file from your hard disk for uploading. Then click the "Upload Selected File" button, the page back, upload the file to the ~/brochures folder. After uploading the file, return to Visual Studio and click the "Refresh" button in the Solution Explorer, and you will see the file just uploaded in the ~/brochures folder.


Figure 14: The file is uploaded to the server


Figure 15: The upload file is saved in the ~/brochures folder

Save uploaded files to file system

There are several important points to note when saving uploaded files to the file system. First is the security issue, to save the file to the file system, the running page must have write permission. If you use Microsoft's Internet Information Services (IIS) as a server, its security depends on the version and settings of IIS.

Another challenge is naming questions about uploading files. In general, when a page saves a file in a ~/brochures folder, it directly uses its original user's computer. For example, user a upload a file named Brochure.pdf, upload Save as ~/brochure/brochure.pdf, if later User B will upload files, and the name is just brochure.pdf, what will happen? As far as our current code is concerned, User B's files will overwrite user A's files.

There are several ways to handle naming conflicts. One is to block uploading files when storing files of the same name. For example, when User B tries to upload a file named Brochure.pdf, it prompts for a name change and tries again. Another method is to use a uniquely identified file name, either the globally unique identifier (GUID), or the primary key value of the corresponding database record. We'll discuss this in more detail in the next tutorial.

Problems faced in processing large-capacity binary data

Tutorial assumes that the binary data processed is moderately sized. Processing binary data with large amounts of data-for example, a few megabytes, or even larger-is beyond the scope of this tutorial. By default, asp.net handles up to 4MB of data, although it can set the maximum value that can be processed in the In addition, uploading large data files is likely to take more time than the asp.net default wait 110 seconds, but also to deal with large data memory, execution efficiency issues.

The FileUpload control is not suitable for uploading large files. When uploading large files, users need to wait patiently and cannot determine whether the upload is in progress. Uploading small files is not a big problem, maybe just a few seconds, while large files can take several minutes. There are many Third-party file upload controls that are better suited for uploading large files and providing progress tips to provide a better user experience.

If your application needs to deal with large files, you should seriously consider the challenges you face and find solutions that are right for you.

Summarize:

Creating an application that processes binary data faces some problems. This tutorial explores 2 of these issues: how to store data and allow users to upload files through a page. The next tutorial explores how to work with binary data in database records and how to display it.

I wish you a happy programming!

Introduction of the author

The author of this series of tutorials, Scott Mitchell, has six asp/asp. NET book, is the founder of 4GuysFromRolla.com, has been applying Microsoft Web technology since 1998. You can click to see all Tutorials "[translation]scott Mitchell asp.net 2.0 data tutorial," I hope to learn asp.net help.

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.