HTML and CSS Reference
In-Depth Information
Uploading Files to the Server
It isn't mandatory that files read by the File API be uploaded to the server. However, in most cases you
upload them to the server so that they can be processed or stored. You can, of course, discard some of the
selected files based on processing logic and upload a subset of the selected files. As far as the File API is
concerned, it doesn't play any role in uploading the files to the server. It's your responsibility to devise a
mechanism that takes care of uploading the required files to the server.
Uploading files selected using a file field control or a custom button is easy because all you need to do
is POST the web form to the server. In the server-side code, you can then access the selected file as shown in
Listing 9-22.
Listing 9-22. Uploading Files by POST ing a Web Form
foreach (HttpPostedFile file in FileUpload1.PostedFiles)
{
string fileName = file.FileName;
fileName = Server.MapPath("~/uploads/" + fileName);
file.SaveAs(fileName);
}
In the server-side code, you use the PostedFiles collection of the FileUpload control. Each element of
PostedFiles is of type HttpPostedFile . The SaveAs() method of the HttpPostedFile class allows you to save
an uploaded file to the server.
Uploading files selected using the drag-and-drop technique is slightly tricky. That's because the
selected files don't belong to a <form> control, and as such they aren't POST ed to the server. You need to
programmatically send them to the server. The jQuery $.ajax() method comes to the rescue here too.
Listing 9-23 shows how you can use $.ajax() to upload files.
Listing 9-23. Using $.ajax() to Upload Files
function UploadFiles() {
var data = new FormData();
for (var i = 0; i < files.length; i++) {
data.append(files[i].name, files[i]);
}
$.ajax({
type: "POST",
url: "UploadFiles.ashx",
contentType: false,
processData: false,
data: data,
success: function (result) {
alert(result);
},
error: function () {
alert("There was error uploading iles!");
}
});
}
This listing shows the UploadFiles() function that uploads the selected files to the server. You can't
send the File objects from the FileList directly to the server; you first need to convert them into FormData
 
Search WWH ::




Custom Search