HTML and CSS Reference
In-Depth Information
objects. As the name suggests, the
FormData
object represents the form data that should accompany the
request. The
append()
method of the
FormData
object allows you to append the individual files that you
wish to upload. The code makes a
POST
request to a generic handler
UploadFiles.ashx
, which is
responsible for accepting the posted files and saving them on the server. Upon successful uploading of the
files, a success message is shown to the user.
Notice that the
$.ajax()
call sets
contentType
and
processData
options to
false
. You don't need to
provide the content type because the
FormData
object defaults to a content type of
multipart/form-data
. If
you don't set the
processData
option to
false
,
$.ajax()
automatically converts the data being posted to
URL-encoded form, which is undesirable.
Listing 9-24 shows how files
POST
ed using the
$.ajax()
method are handled on the server side using
the generic handler
UploadFiles.ashx
.
Listing 9-24.
Saving Files Uploaded Using a Generic Handler
public void ProcessRequest(HttpContext context)
{
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
foreach (string key in files)
{
HttpPostedFile file = files[key];
string fileName = file.FileName;
fileName = context.Server.MapPath("~/uploads/" + fileName);
file.SaveAs(fileName);
}
}
context.Response.ContentType = "text/plain";
context.Response.Write("File Uploaded Successfully!");
}
The generic handler's
ProcessRequest()
method saves the posted file on the server. ProcessRequest()
receives
HttpContext
as a parameter. This can be used to access intrinsic objects such as
Request
,
Response
,
and
Server
.
The uploaded files are accessed using the
Request.Files
collection. Each element of the
Files
collection is of type
HttpPostedFile
. The
SaveAs()
method of the
HttpPostedFile
class allows you to save a
file on the server. Once all the files are saved, a success message is sent to the client. This message is
displayed in the
success
function of the
$.ajax()
call.
Using the File API in ASP.NET MVC
In this section, you develop an ASP.NET MVC application that uses the File API. The application is
intended to serve two purposes: upload XML files to the server, and validate the uploaded files against an
XSD schema.
Consider a hypothetical situation in which a desktop application stores its data as XML files on the
local machine. Periodically you're required to upload the XML files thus generated to a central web server
for further processing. Such an application can use the File API to do the following:
• Ensure that only XML iles are being uploaded to the server.