1. Trang chủ
  2. » Công Nghệ Thông Tin

ASP.NET 4 Unleased - p 22 pdf

10 254 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 585,1 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

To save a file to the file system, the Windows account associated with the ASP.NET page must have sufficient permissions to save the file.. To enable ASP.NET Framework to save an uploade

Trang 1

The page includes a method named CheckFileType(), which prevents users from

upload-ing a file that does not have the gif, jpeg, jpg, or png extension The method restricts

the type of file that can be uploaded based on the file extension

NOTE

The HTML 4.01 specifications define an accept attribute that you can use to filter the

files that can be uploaded Unfortunately, no browser supports the accept attribute, so

you must perform filtering on the server (or use some JavaScript to check the filename

extension on the client)

To save a file to the file system, the Windows account associated with the ASP.NET page

must have sufficient permissions to save the file For Windows 2003 and Windows 2008

servers, an ASP.NET page executes in the security context of the NETWORK SERVICE

account In the case of every other operating system, an ASP.NET page executes in the

security context of the ASPNET account

To enable ASP.NET Framework to save an uploaded file to a particular folder, you need to

right-click the folder within Windows Explorer, select the Security tab, and provide

either the NETWORK SERVICE or ASPNET account Write permissions for the folder (see

Figure 4.2)

FIGURE 4.2 Adding Write permissions for the ASPNET account

Trang 2

Saving Files to a Database

You also can use the FileUpload control to save files to a database table Saving and

retrieving files from a database can place more stress on your server However, it does have

certain advantages First, you can avoid file system permissions issues Second, saving files

to a database enables you to more easily back up your information

The page in Listing 4.2 enables you to save Microsoft Word documents to a database table

(see Figure 4.3)

LISTING 4.2 FileUploadDatabase.aspx

<%@ Page Language=”C#” %>

<%@ Import Namespace=”System.IO” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<script runat=”server”>

protected void btnAdd_Click(object sender, EventArgs e)

{

if (upFile.HasFile)

{

if (CheckFileType(upFile.FileName))

srcFiles.Insert();

}

}

bool CheckFileType(string fileName)

{

return (Path.GetExtension(fileName).ToLower() == “.doc”

|| Path.GetExtension(fileName).ToLower() == “.docx”);

}

</script>

<html xmlns=”http://www.w3.org/1999/xhtml” >

<head id=”Head1” runat=”server”>

<style type=”text/css”>

.fileList li

{

margin-bottom:5px;

}

</style>

<title>FileUpload Database</title>

</head>

<body>

<form id=”form1” runat=”server”>

<div>

Trang 3

<asp:Label

id=”lblFile”

Text=”Word Document:”

AssociatedControlID=”upFile”

Runat=”server” />

<asp:FileUpload

id=”upFile”

Runat=”server” />

<asp:Button

id=”btnAdd”

Text=”Add Document”

OnClick=”btnAdd_Click”

Runat=”server” />

<hr />

<asp:Repeater

id=”rptFiles”

DataSourceID=”srcFiles”

Runat=”server”>

<HeaderTemplate>

<ul class=”fileList”>

</HeaderTemplate>

<ItemTemplate>

<li>

<asp:HyperLink

id=”lnkFile”

Text=’<%#Eval(“FileName”)%>’

NavigateUrl=’<%#Eval(“Id”, “~/FileHandler.ashx?id={0}”)%>’

Runat=”server” />

</li>

</ItemTemplate>

<FooterTemplate>

</ul>

</FooterTemplate>

</asp:Repeater>

<asp:SqlDataSource

id=”srcFiles”

ConnectionString=”Server=.\SQLExpress;Integrated Security=True;

AttachDbFileName=|DataDirectory|FilesDB.mdf;User Instance=True”

SelectCommand=”SELECT Id,FileName FROM Files”

InsertCommand=”INSERT Files (FileName,FileBytes) VALUES

➥(@FileName,@FileBytes)”

Trang 4

FIGURE 4.3 Uploading Microsoft Word documents

Runat=”server”>

<InsertParameters>

<asp:ControlParameter Name=”FileName” ControlID=”upFile”

PropertyName=”FileName” />

<asp:ControlParameter Name=”FileBytes” ControlID=”upFile”

PropertyName=”FileBytes” />

</InsertParameters>

</asp:SqlDataSource>

</div>

</form>

</body>

</html>

When you submit the form in Listing 4.2, the btnAdd_Click() method executes This

method checks the file extension to verify that the file is a Microsoft Word document

Next, the SqlDataSource control’s Insert() method is called to insert the values of the

FileUpload control’s FileName and FileBytes properties into a local SQL Express database

table The SQL Express database table, named Files, looks like this:

Trang 5

The page also displays a list of the current Microsoft Word documents in the database You

can click any file and view the contents of the file Exactly what happens when you click

a file is browser (and browser settings) dependent With Microsoft Internet Explorer, for

example, the document opens directly in the browser

Clicking the name of a document links you to a page named FileHandler.ashx The

FileHandler.ashx file is a generic HTTP Handler file Chapter 25, “Using the ASP.NET URL

Routing Engine,” discusses HTTP Handlers in detail An HTTP Handler enables you to

execute code when someone makes a request for a file with a certain path

The FileHandler.ashx file is contained in Listing 4.3

LISTING 4.3 FileHandler.ashx

<%@ WebHandler Language=”C#” Class=”FileHandler” %>

using System;

using System.Web;

using System.Data;

using System.Data.SqlClient;

public class FileHandler : IHttpHandler {

const string conString = @”Server=.\SQLExpress;Integrated Security=True;

AttachDbFileName=|DataDirectory|FilesDB.mdf;User Instance=True”;

public void ProcessRequest (HttpContext context) {

context.Response.ContentType = “application/msword”;

SqlConnection con = new SqlConnection(conString);

SqlCommand cmd = new SqlCommand(“SELECT FileBytes FROM Files WHERE

➥Id=@Id”, con);

cmd.Parameters.AddWithValue(“@Id”, context.Request[“Id”]);

using (con)

{

con.Open();

byte[] file = (byte[])cmd.ExecuteScalar();

context.Response.BinaryWrite(file);

}

FileBytes Varbinary(max)

Trang 6

}

public bool IsReusable {

get {

return false;

}

}

}

When the FileHandler.aspx page is requested, the ProcessRequest() method executes

This method grabs a query string item named Id and retrieves the matching record from

the Files database table The record contains the contents of a Microsoft Word document

as a byte array The byte array is sent to the browser with the Response.BinaryWrite()

method

Uploading Large Files

You must do extra work when uploading large files You don’t want to consume your

entire server’s memory by placing the entire file in memory When working with a large

file, you need to work with the file in more manageable chunks

First, you need to configure your application to handle large files Two configuration

settings have an effect on posting large files to the server: the httpRuntime

maxRequestLength and httpRuntime requestLengthDiskThreshold settings

The maxRequestLength setting places a limit on the largest form post that the server can

accept By default, you cannot post a form that contains more than 4MB of data—if you

try, you get an exception If you need to upload a file that contains more than four

megabytes of data, you need to change this setting

The requestLengthDiskThreshold setting determines how a form post is buffered to the

file system In an older version of ASP.NET (ASP.NET 1.1), uploading a large file could do

horrible things to your server The entire file was uploaded into the server memory While

a 10-megabyte video file was uploaded, for example, 10 megabytes of server memory was

consumed

The ASP.NET 4 Framework enables you to buffer large files onto the file system When the

size of the file passes the requestLengthDiskThreshold setting, the remainder of the file is

buffered to the file system (in the Temporary ASP.NET Files folder)

By default, the ASP.NET framework is configured to buffer any post larger than

80KB to a file buffer If you are not happy with this setting, you can modify the

requestLengthDiskThreshold to configure a new threshold (The

requestLengthDiskThreshold setting must be less than the maxRequestLength setting.)

The web configuration file in Listing 4.4 enables files up to 10MB to be posted It also

changes the buffering threshold to 100KB Changing the buffering threshold controls the

amount of information stored in memory before it is flushed to disk

Trang 7

LISTING 4.4 Web.Config

<?xml version=”1.0”?>

<configuration>

<system.web>

<httpRuntime

maxRequestLength=”10240”

requestLengthDiskThreshold=”100” />

</system.web>

</configuration>

When working with large files, you must be careful about the way that you handle the

file when storing or retrieving the file from a data store For example, when saving or

retrieving a file from a database table, you should never load the entire file into memory

The page in Listing 4.5 demonstrates how you can save a large file to a database table

efficiently

LISTING 4.5 FileUploadLarge.aspx

<%@ Page Language=”C#” %>

<%@ Import Namespace=”System.IO” %>

<%@ Import Namespace=”System.Data” %>

<%@ Import Namespace=”System.Data.SqlClient” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<script runat=”server”>

const string conString = @”Server=.\SQLExpress;Integrated Security=True;

AttachDbFileName=|DataDirectory|FilesDB.mdf;User Instance=True”;

void btnAdd_Click(Object s, EventArgs e)

{

if (upFile.HasFile)

{

if (CheckFileType(upFile.FileName))

{

AddFile(upFile.FileName, upFile.FileContent);

rptFiles.DataBind();

}

}

}

bool CheckFileType(string fileName)

{

Trang 8

return Path.GetExtension(fileName).ToLower() == “.doc”;

}

void AddFile(string fileName, Stream upload)

{

SqlConnection con = new SqlConnection(conString);

SqlCommand cmd = new SqlCommand(“INSERT Files (FileName) Values

➥(@FileName);” +

“SELECT @Identity = SCOPE_IDENTITY()”, con);

cmd.Parameters.AddWithValue(“@FileName”, fileName);

SqlParameter idParm = cmd.Parameters.Add(“@Identity”, SqlDbType.Int);

idParm.Direction = ParameterDirection.Output;

using (con)

{

con.Open();

cmd.ExecuteNonQuery();

int newFileId = (int)idParm.Value;

StoreFile(newFileId, upload, con);

}

}

void StoreFile(int fileId, Stream upload, SqlConnection connection)

{

int bufferLen = 8040;

BinaryReader br = new BinaryReader(upload);

byte[] chunk = br.ReadBytes(bufferLen);

SqlCommand cmd = new SqlCommand(“UPDATE Files SET FileBytes=@Buffer WHERE

Id=@FileId”, connection);

cmd.Parameters.AddWithValue(“@FileId”, fileId);

cmd.Parameters.Add(“@Buffer”, SqlDbType.VarBinary, bufferLen).Value = chunk;

cmd.ExecuteNonQuery();

SqlCommand cmdAppend = new SqlCommand(“UPDATE Files SET FileBytes

➥.WRITE(@Buffer,NULL, 0) WHERE Id=@FileId”, connection);

cmdAppend.Parameters.AddWithValue(“@FileId”, fileId);

cmdAppend.Parameters.Add(“@Buffer”, SqlDbType.VarBinary, bufferLen);

chunk = br.ReadBytes(bufferLen);

while (chunk.Length > 0)

{

cmdAppend.Parameters[“@Buffer”].Value = chunk;

cmdAppend.ExecuteNonQuery();

Trang 9

chunk = br.ReadBytes(bufferLen);

}

br.Close();

}

</script>

<html xmlns=”http://www.w3.org/1999/xhtml” >

<head id=”Head1” runat=”server”>

<title>FileUpload Large</title>

</head>

<body>

<form id=”form1” runat=”server”>

<div>

<asp:Label

id=”lblFile”

Text=”Word Document:”

AssociatedControlID=”upFile”

Runat=”server” />

<asp:FileUpload

id=”upFile”

Runat=”server” />

<asp:Button

id=”btnAdd”

Text=”Add Document”

OnClick=”btnAdd_Click”

Runat=”server” />

<hr />

<asp:Repeater

id=”rptFiles”

DataSourceID=”srcFiles”

Runat=”server”>

<HeaderTemplate>

<ul class=”fileList”>

</HeaderTemplate>

<ItemTemplate>

<li>

<asp:HyperLink

id=”lnkFile”

Trang 10

Text=’<%#Eval(“FileName”)%>’

NavigateUrl=’<%#Eval(“Id”, “~/FileHandlerLarge.ashx?id={0}”)%>’

Runat=”server” />

</li>

</ItemTemplate>

<FooterTemplate>

</ul>

</FooterTemplate>

</asp:Repeater>

<asp:SqlDataSource

id=”srcFiles”

ConnectionString=”Server=.\SQLExpress;Integrated Security=True;

AttachDbFileName=|DataDirectory|FilesDB.mdf;User Instance=True”

SelectCommand=”SELECT Id,FileName FROM Files”

Runat=”server” />

</div>

</form>

</body>

</html>

In Listing 4.5, the AddFile() method is called This method adds a new row to the Files

database table that contains the filename Next, the StoreFile() method is called This

method adds the actual bytes of the uploaded file to the database The file contents are

divided into 8040-byte chunks The SQL UPDATE statement includes a WRITE clause used

when the FileBytes database column is updated

NOTE

Microsoft recommends that you set the buffer size to multiples of 8,040 when using

the WRITE clause to update database data

The page in Listing 4.5 never represents the entire uploaded file in memory The file is

yanked into memory from the file system in 8,040-byte chunks and fed to SQL Server in

chunks

When you click a filename, the FileHandlerLarge.ashx HTTP Handler executes This

handler retrieves the selected file from the database and sends it to the browser The

handler is contained in Listing 4.6

Ngày đăng: 06/07/2014, 18:20

TỪ KHÓA LIÊN QUAN