59
ASP.NET Web Pages Using The Razor Syntax
Chapter 8 – Working with Files
123
<!DOCTYPE html>
<html>
<head>
<title>FileUpload - Single-File Example</title>
</head>
<body>
<h1>FileUpload - Single-File Example</h1>
@FileUpload.GetHtml(
initialNumberOfFiles:1,
allowMoreFilesToBeAdded:false,
includeFormTag:true,
uploadText:"Upload")
@if (IsPost) {
<span>File uploaded!</span><br/>
}
</body>
</html>
The body portion of the page uses the
FileUpload
helper to create the upload box and buttons
that you're probably familiar with:
The properties that you set for the
FileUpload
helper specify that you want a single box for the
file to upload and that you want the submit button to read Upload. (You'll add more boxes later
in the chapter.)
When the user clicks Upload, the code at the top of the page gets the file and saves it. The
Request
object that you normally use to get values from form fields also has a
Files
array that
contains the file (or files) that have been uploaded. You can get individual files out of specific
positions in the array — for example, to get the first uploaded file, you get
Request.Files[0]
, to
get the second file, you get
Request.Files[1]
, and so on. (Remember that in programming,
counting usually starts at zero.)
When you fetch an uploaded file, you put it in a variable (here,
uploadedFile
) so that you can
manipulate it. To determine the name of the uploaded file, you just get its
FileName
property.
However, when the user uploads a file,
FileName
contains the user's original name, which
includes the entire path. It might look like this:
C:\Users\Public\Sample.txt
You don't want all that path information, though, because that's the path on the user's
computer, not for your server. You just want the actual file name (Sample.txt). You can strip out
just the file from a path by using the
Path.GetFileName
method, like this:
Path.GetFileName(uploadedFile.FileName)