This article mainly introduces the method of directly displaying pdf hyperlinks in asp.net 2.0.And how to display the image saved in the form of binary data in the gridview,Although this method is rarely used in actual development,But it's still worth learning.


In the previous tutorial, we explained two modes of application processing binary data, and upload files from browser to server file system using fileupload control.When files are uploaded and stored in the file system,The storage path of the file should be stored in the corresponding database record.

Let's first look at how to provide binary data to end users.How to display binary data?It depends on its type.Like pictures,We display it as an image;if it's a pdfs, Microsoft Word document, zip file, or other type of data,It might be more appropriate to provide a "download" link.

In this section, we look at how to present binary data in data web controls such as gridview and detailsview.In a later tutorial we will turn our attention to linking uploaded files to the database.

Step 1:Provide the brochurepath value

The picture column of the categories category stores picture information of related classes.Specifically,16-color low-quality bitmap,The size is 172 by 120 pixels, which is about 11 kb. It also includes an ole header of about 78 bytes, which needs to be stripped when displaying the picture.Why is there a header?Because the database northwind is derived from Microsoft's access database. The binary data ole type is stored in access,This type adds a header.Now let ’s see how to strip the header from the picture,For display.In a later tutorial we will create an interface,Replace these bitmaps with headers with equivalent jpg images without headers.

Before we examined how to use the fileupload control, let us continue to add files to the server file system.But you don't need to update the categorypath column of the categories table for the time being, which is the content of the next chapter.We now need to manually assign a value to the brochurepath.

In this tutorial,When you download something,You can see that there are 7 pdf booklets in the ~/brochures7 folder, each of which corresponds to a category,Except seafood. I deliberately did not provide a pdf brochure for seafood in order to explore how to handle cases where some records are not accompanied by binary data.Right-click categories in Server Explorer, select "View Table Data", enter the file path,As shown in Figure 1. Since the seafood class has no picture,Set its brochurepath value to "null".

Figure 1:Manually typing values ​​for the brochurepath column of the categories

Step 2:Add a download link in gridview

After assigning a value to the brochurepath column of the table categories,We are going to create a gridview to show each kind,A link is provided to download a brochure for each category.In step 4 we will extend the gridview to display pictures for each class.

Open the displayordownloaddata.aspx page of the binarydata folder and enter the design mode,Drag a gridview control from the toolbox to the page,Let its id be categories and select from its smart tag to bind to an objectdatasource control named categoriesdatasource. The control calls the getcategories () method of the categories categorybll.

Figure 2:Create an objectdatasource control named categoriesdatasource

Figure 3:Setting the objectdatasource to use the categoriesbll class

Figure 4:Calling the getcategories () method

After setting up,visual studio automatically generates boundfield for categoryid, categoryname, description, numberofproducts and brochurepath. Remove numberofproducts because the getcategories () method doesn't work,The categoryid is also removed. Change the headertext attributes of categoryname and brochurepath to "category" and "brochure", respectively. After making the above modifications,Your gridview and objectdatasource declaration code should look like this:

<asp:gridview runat="server"
 autogeneratecolumns="false" datakeynames="categoryid"
 datasourceid="categoriesdatasource" enableviewstate="false">
 <asp:boundfield datafield="categoryname" headertext="category"
  sortexpression="categoryname" />
 <asp:boundfield datafield="description" headertext="description"
  sortexpression="description" />
 <asp:boundfield datafield="brochurepath" headertext="brochure"
  sortexpression="brochurepath" />
<asp:objectdatasource runat="server"
 oldvaluesparameterformatstring="original_ {0}"
 selectmethod="getcategories" typename="categoriesbll">

View View this page in your browser (see Figure 5). All 8 classes are listed. Except seafood, the boundfield column of the other 7 classes shows their own broochpath values. Since the seafoodpath of the seafood is null, it looks like a space.

Figure 5:Name, description and brochurepath values ​​for each category

Instead of displaying the text value of the brochurepath, it is better to create a link to the brochure.Remove brochurepath and replace it with hyperlinkfield. Set its headertext property to "brochure", text property to "view brochure", and datanavigateurlfields property to "brochurepath".

Figure 6:Adding a hyperlinkfield to the brochurepath

This will add a list of links in the gridview,As shown in Figure 7. When clicking "view brochure", either display the pdf directly in the browser or prompt the user to download the file.It depends on your browser settings and whether a pdf reader is installed.

Figure 7:Click on "view brochure" to access a category of brochure

Figure 8:Showing a certain type of pdf file

Hide "view brochure" text for classes without brochure images

As shown in Figure 7, a hyperlinkfield named brochurepath is rendered as its text attribute ("view brochure") regardless of whether a class's brochurepath is null or not. Of course, if brochurepath is null, the link is only displayed as text (without underscores), just like the seafood class (see Figure 7). Rather than displaying the text "view brochure", it is more preferable to show those classes with a blank path value as "no brochure available".

To this end,We need to use templatefield to produce a suitable result based on the value of the broochpath.Let ’s take a look at how to achieve it,Just like in Tutorial 12Use templatefield in gridview control"same.

Selected In the "Edit Column" dialog box, select the hyperlinkfield named brochurepath, and then click the "convert this field into a templatefield" link to convert it to templatefield.

Figure 9:Converting hyperlinkfield to templatefield

This will create a templatefield whose itemtemplate template contains a hyperlink web control with the navigationurl property of the control as the brochurepath value. Replace it with the following code:

<asp:templatefield headertext="brochure">
 <%#generatebrochurelink (eval ("brochurepath"))%>

Then, add a protected type generatebrochurelink method in the "Backend Code" of the asp.net page, which takes an input parameter and returns a string.

protected string generatebrochurelink (object brochurepath)
 if (convert.isdbnull (brochurepath))
 return "no brochure available";
 return string.format (@ "<a href =" "{0}" ">view brochure</a>",  resolveurl (brochurepath.tostring ()));

This method determines whether the value passed in is null. If so, a message is returned stating that there are no brochure files in this category;Conversely, if the incoming value is not empty,Will appear as a link.We have noticed,When the brochurepath value is not empty,The resolveurl (url) method will be called. The role of this method is to convert the incoming relative path into a physical path.For example, the root directory of the application is/tutorial55. The path returned by resolveurl ("~/brochures/meats.pdf") is /tutorial55/brochures/meat.pdf.

Figure 10 shows the modified interface.We noticed that the seafoodpath column of the seafood class now shows the text "no brochure available".

Figure 10:Classes without brochures will be displayed with the text "no brochure available"

Step 3:Add a page to display class pictures

user When a user visits an asp.net page, he will receive the html code of the page. The html code contains only text, and does not contain any binary data.Any binary data,Like pictures,Music files, flash programs, windows media player videos, etc. are stored on the server as independent resources.

Html contains only references to these files,These files are not included.

For example, theelement is used to reference an image in html,Its src attribute points to the image file,Such as:

<img src="mypicture.jpg" ... />

When the browser receives the html code, it sends a request for the image to the server and displays it in the browser,This mode works for all binary data.In step 2, we did not display the brochure in the browser in the html tag of the page,Instead, provide a hyperlink in the html tag,When clicked it was,Causes the browser to request the pdf file directly.

display To display or allow users to download binary data stored in a database,We need to create another page,Used to return the required data from the database.For our application,Since there is only one item of binary data stored directly in the database-a class picture,So we need a page,Returns a picture of a particular class from the database when needed.

Add to Add a displaycategorypicture.aspx page to the binarydata folder. Be careful not to use the master page.The page accepts a query string containing the categoryid value,Returns the binary data of the picture column.Since the page only returns binary data,So we don't need any code in the html part of the page.Enter the "source" mode of the page, delete all the code of the page,Keep only the<%@page%>section. That is:the declaration code of the displaycategorypicture.aspx page should consist of only the following separate lines:

<%@page language="c#" autoeventwireup="true"

If<%@page%>contains the masterpagefile attribute, delete it,At the same time, add the following code to the page_load event handler of the background code class:

protected void page_load (object sender, eventargs e)
 int categoryid=convert.toint32 (request.querystring ["categoryid"]);
 //get information about the specified category
 categoriesbll categoryapi=new categoriesbll ();
 northwind.categoriesdatatable categories =
 categoryapi.getcategorywithbinarydatabycategoryid (categoryid);
 northwind.categoriesrow category=categories [0];
 //output http headers providing information about the binary data
 //output the binary data
 //but first we need to strip out the ole header
 const int oleheaderlength=78;
 int strippedimagelength=category.picture.length-oleheaderlength;
 byte [] strippedimagedata=new byte [strippedimagelength];
 array.copy (category.picture, oleheaderlength, strippedimagedata, 0, strippedimagelength);
 response.binarywrite (strippedimagedata);

The code first reads the categoryid value of the query string and assigns a value to the variable named categoryid.Then, by calling the categoriesbll class,

getcategorywithbinarydatabycategoryid (categoryid) method to obtain image data,Then use the response.binarywrite (data) method to return data to the client.But before that we need to strip the ole header of the data. How to achieve it?Create a byte array named strippedimagedata, which contains exactly 78 fewer bytes than the picture column. The array.copy method will copy data from the 78th byte of category.picture (ie, just strip the ole header).

The response.contenttype property in the code specifies the mime type of the content to return so that the browser knows how to display the data.Because the picture column of the categories table stores bitmap pictures,So here,The bitmap image's mime type is (image/bmp). If you ignore the mime type, most browsers can also display the image correctly,Because they can infer the type of the image file based on the contents of the binary data.Even so,Still use mime types whenever possible.

After creating the page,Can visit the page

displaycategorypicture.aspx?categoryid=categoryid to view pictures of a particular category.Figure 11 shows a picture of the beverages class.Page is


Figure 11:Picture showing class beverages

Sometimes, when you visit the displaycategorypicture.aspx&categoryid=categoryid page, there may be a prompt:"unable to cast object of type" system.dbnull "to type" system.byte [] "". The reasons may be as follows. First, the picture column of the categories category is allowed to be null, and the displaycategorypicture.aspx page always assumes that a non-null value is passed in. When picture is null, you cannot directly access the picture property of categoriesdatatable. If you allow picture to be null, add the following code:

if (category.ispicturenull ())
 //display some "no image available" picture
 response.redirect ("~/images/nopictureavailable.gif");
 //send back the binary contents of the picture column
 //... set contenttype property and write out ...
 //... data via response.binarywrite ...

The above code assumes that there is a picture named nopictureavailable.gif in the images folder. When there is no picture in a certain category,The picture is displayed.

Another situation:When you use the "use SQL statement" mode in the wizard to run the main query again,It will affect the columns returned by the select command of the getcategorywithbinarydatabycategoryid method (in other words,The main query does not return the picture column. When the main query is run again, the getcategorywithbinarydatabycategoryid method will not return the picture column. Therefore, make sure that the select command of the getcategorywithbinarydatabycategoryid method returns the picture column.

Note:Every time you visit the displaycategorypicture.aspx page, you will access the database and return the required picture.If the picture hasn't changed since the last visit,In this way, the method of returning data every time you access the database is not efficient.Fortunately,http allows the use of conditional gets, in which case,The client makes an http request send an if-modified-since http header. The if-modified-since http header contains the latest data and time the client obtained from the server.If the requested content has not changed,The server responded with a not modified status code (304) and did not return the requested content.in short,If the requested resource hasn't sent changes since its most recent visit,The server will not return the resource,In order to reduce the load on the server.

Step 4:Display category pictures in the gridview control

Now we have a web page to display a certain kind of picture.Point to the displaycategorypicture.aspx&categoryid=categoryid page through the image web control or html<img>element to achieve the purpose of displaying the picture.We can display images in the imagefield of the gridview control or detailsview control.The dataimageurlfield attribute and dataimageurlformatstring attribute of imagefield are similar to the datanavigateurlfields attribute and datanavigateurlformatstring attribute of hyperlinkfield.

Let's extend the gridview control named categories in the displayordownloaddata.aspx page.Add an imagefield and set its dataimageurlfield property to categoryid;

The dataimageurlformatstring property is displaycategorypicture.aspx&categoryid={0}. This will add a column to the gridview,Rendered as anelement with a src attribute of displaycategorypicture.aspx?categoryid={0}, where {0} will be populated by the categoryid value of the gridview row.

Figure 12:Adding an imagefield to the gridview control

After adding,The declaration code for your gridview control should look like this:

<asp:gridview runat="server" autogeneratecolumns="false"
 datakeynames="categoryid" datasourceid="categoriesdatasource"
 <asp:boundfield datafield="categoryname" headertext="category"
  sortexpression="categoryname" />
 <asp:boundfield datafield="description" headertext="description"
  sortexpression="description" />
 <asp:templatefield headertext="brochure">
  <%#generatebrochurelink (eval ("brochurepath"))%>
 <asp:imagefield dataimageurlfield="categoryid"

Take a few minutes to view the page in your browser,Note that each line of the record now contains a picture of that type.

Figure 13:Each line of records shows a picture

to sum up:

In this section we explored how to display binary data,How the data is presented depends on its type.For pdf brochure files,We provide a "view brochure" link, and when clicked,Direct users to pdf brochure files.For a certain kind of picture,We first create a page to fetch and display it from the database,Then display the picture in a gridview control.Now that you saw how to display binary data,We are going to explore how to perform insert, update, and delete operations on it.In the next tutorial, we will see how to associate uploaded files with corresponding database records.Then, we will discuss how to update the existing binary data.And how to delete the corresponding binary data when deleting database records.

Happy programming!

About the Author

  • Previous WEB front-end development framework Bootstrap3 VS Foundation5
  • Next ThinkPHP custom Redis implementation method for SESSION