Watch videos with subtitles in your language, upload your videos, create your own subtitles! Click here to learn more on "how to Dotsub"

[How Do I:] Simple File Uploads in ASP.NET

0 (0 Likes / 0 Dislikes)
  • Embed Video

  • Embed normal player Copy to Clipboard
  • Embed a smaller player Copy to Clipboard
  • Advanced Embedding Options
  • Embed Video With Transcription

  • Embed with transcription beside video Copy to Clipboard
  • Embed with transcription below video Copy to Clipboard
  • Embed transcript

  • Embed transcript in:
    Copy to Clipboard
  • Invite a user to Dotsub
[Microsoft] [] [Male speaker] In this video I'll demonstrate using to upload files from the client's machine up to your server. This will be the first in a 4-part series of uploading videos, each video illustrating a different pattern that you can use to upload files in your application. Some folks have asked that I demonstrate the finished application before we start building from scratch. This is the application that we're going to build. Notice, very simple. It has a text box with a browse button. I click on the browse button and go navigate to the file that I want to upload. Then I'll click on the "go" button. The upload target is this directory in the root of my C drive called uploaded user files, and you notice that it's empty right now. When I click on the "go" button notice it provides me with feedback, so the full path on the user's machine where the file was uploaded from, the type of the file—in this case my type is an image/gif file— and the size, as well as the message that says the file was uploaded successfully. Then if we look in the uploaded user files directory that was previously empty, we can see that the file that I selected has now been successfully uploaded. Let's go ahead and delete me from that directory and, in fact let's go up one level and delete the directory completely. Now let's go ahead and start a fresh copy of Visual Web Developer. Let's create a new website. We'll hop into design mode and go over to our control toolbox, scroll down a little bit, and we'll find the file upload control. So in this, the first of the 4 videos on uploading, we're going to assume a static number of files to be uploaded, and that number needs to be known at design time. In our case it will be just 1 file. Having done that, let's go into split mode and do a little formatting. Let's begin by giving the page a proper title: ASP.NET File Upload. Then we'll grab this down here in our body. We'll make a bold header section and do that as well. Now here, just above our file upload field, we'll provide some hints to the users, so we'll say, "Please choose the file that you would like to upload." Let's change the name of this form to something more meaningful—formFileUpload— and also let's change the upload controls ID to something more meaningful— Call it FileField since that's what it is. I also want to change the width of this. You note that when we drop on the page—you'll note that it's a little short, so let's give ourselves some spacing and then, in that control, let's set the size, which is the number of characters that the box is sized to accept. Let's set that to 60. There you can see we've got plenty of room to see the path of the file that we choose. Now this button right here—this browse button—that's what opens up the file dialog that let's us select the file that we want to upload, so we're going to need a button whose click event can actually cause us to process the upload request. Let's change that button ID to UploadButton. The button just said "go" in the original demo that I showed you, but let's make it something more meaningful, say, "Click to process your upload." Let's go into full source mode here and just do a little spacing clean up. Over here I'm going to—just for formatting's sake, I'm going to add a horizontal rule and another break, and then down here we need to create an area where we can display those file attributes like name, contents, type, size, etcetera, so we're going to do that here. We'll create a div, and we'll give that div an ID of UploadDetails, and since we don't want to show this until after the file has been uploaded let's set the visible property equal to false, and of course we're going to access elements inside this div in our Visual Basic code-behind so we want to set the runat attribute equal to server. Now inside this div we're going to need a place for each of the file attributes that we want it to display, so we had file name, file content type, and file size. In order to have an element that we can program against on the server let's create a span for each of these artifacts that we want to display to the user. Let's set the span. We'll set the ID equal to whatever the attribute is that we're displaying, so in this case file name, and of course we're going to populate these on the server so we need runat server. Close the tag. Then we want each of these to appear on a line by itself so we'll put breaks in, and I'm going to use the magic of cut and paste to get all 3 of the attributes that we want to display, changing the names of course to match the content type that we're displaying. The last thing that we need is a place where we can put the success or failure message, so let's create a span and we can just call it anything we want—"Span1" I guess. I'm going to set a color, and I'm just going to use a static color so I'm going to say set the color equal to red. You could be a lot more creative in that you could set the color based on what type of message you're displaying. You might dynamically set the color to say display it in red if you're displaying an error message, otherwise use the default color if no error occurred, or you could get as creative as you like. In our case I'm just going to use red. Okay, so here's our user interface. The first thing that we're going to need is we're going to need a page load event handler, and for us, we're going to use a page load event handler to check and see if the upload directory exists and to create one if it doesn't exist. Now we're going to create one in the root of our C drive, but there are a couple of suggestions that I'd like to make. I'm going to do it in the root of my C drive because I'm doing this on my laptop and it only has 1 drive, but I highly recommend that you don't create a user upload directory in the same file structure as your operating system or your web server software, so it would be great if you could use a separate hard drive or a separate partition and, in fact, most web servers are configured to allow you to do this. In any event, you want to make sure that you are creating this upload directory structure someplace that is secure, that you can apply quotas, etcetera. The other thing—speaking of quotas—you can be pretty creative in terms of how you do this. I'm just going to use a static path name for uploading my files, but you can take this to the next level by keying off user identity for example or the user's role, so if you're using Windows authentication you could use the Windows identity. If you're using forms-based authentication you could use the log in name and create a directory for each user if you wanted to be user specific, or you could use some sort grouping mechanism or roles, whether they're active directory roles or just role types in your form space authentication, to create a group of directories for users, and if you wanted to go even one step beyond that you could use the operating system, and when you create these directories set things like quotas or specific permissions on those directories. So you can get as advanced as you like dependent on the semantics of your application. In our case, as I mentioned, we're just going to create an uploaded user files directory. So I'm going to need a couple of string variables here. One will be UpPath As String. The other will be UpName As String. Let's set the path name here and, again, I'm just going to set this as a static text. You could store this in a config file or a data base, and I would highly recommend that you do that so that if you ever need to change it you don't have to rebuild your application to do it. Uploaded user files. Now let's just get the name of the directory. So we do that with— Obviously if you're a C# programmer this mechanism is a little bit different, but there's C# code available for download as well. I'm happening to do the video here using VB, but there will be C# code available for download that will show you the C# mechanism for doing this. So now that I've got that, now I can just say if that directory name doesn't exist then let's create it. We say make directory. Add the trailing slash and there we go. All right. The next thing that I need is the click event handler. This is where we're actually going to do the upload. There are a couple of things that we're going to do here. The first thing, remember, is that we have this object by virtue of this control so this control that we named FileField contains an object called PostedFile, and PostedFile is going to give us all that information—file name, content type, content length—that we wanted to display here. Let's go here and say FileName—and remember that's a span, so we need to populate the inner HTML or inner text with FileField.PostedFile.FileName, FileContent.InnerHtml, FileField.PostedFile.ContentType, and then lastly, FileSize.InnerHtml. = FileField.PostedFile.ContentLength. The last thing that we need to do is we need to take that UploadDetails div and set its visible attribute to true again so that it will be displayed. Now we can go ahead and try and create the file itself. Let's say Dim myFileName As String and we're going to get the file name from the posted file object of our file field. Next, Dim C As String = System.IO.Path.GetFileName (myFileName) and now we can actually try and save the file. We'll create a Try-Catch block, and we'll say FileField.PostedFile.SaveAs and we're going to grab that directory name as a string that we wanted to save it into and append the file name. Assuming that succeeded, the other thing that we want to do is add a message to that Span1 span that we created that says, "File upload Successful." Now if there is an error can do whatever error handling is appropriate. In our case we'll just say, "File upload failed." Then one other thing that we want to do is that even though we may have this file information, we don't want to display it if the upload failed, so we'll set that visible back to equals false. This is an unexpected circumstance. It shouldn't happen, but we're adding error handling as is appropriate. That should do it. Now let's go ahead and let's make sure that that directory is missing. Now we can go ahead and run our application. Note now the UploadedUserFiles was automatically created because it didn't previously exist. Now we go out and fetch a file. Let's grab that one. "Upload successful" tells us the directory on the user's machine— where his browser is running—that that file was uploaded from, the content type, the number of bytes, and our message. If we go out here we notice that the file has been successfully uploaded. Now one thing that I do want to remind you of here is that I've shown you how to do the file uploading, you need to secure your application based on the needs of that application, so, for example, in most cases you probably don't want to allow folks to upload zip files, or at least executable files. You might let them upload zip files. If that's the case, before you call this SaveAs method, you're going to want to check the file type and make sure that it's not an executable file, or a script file, or anything that you don't want to be uploaded. If you need to upload files like exe files I suggest that you automatically change the file extension to something that the operating system can't execute. So you want to make sure that you implement that security based on the needs of your application. That's it. It's that easy to use the file upload control to upload files in your application. Hopefully you'll watch the other 3 upload videos that are being published and look at some of the different ways that you can enhance the upload capabilities of your applications.

Video Details

Duration: 17 minutes and 17 seconds
Country: United States
Language: English
License: All rights reserved
Genre: None
Views: 8
Posted by: neudesicasp on Aug 26, 2013

In this video I will demonstrate, using ASP.NET, uploading a single file from the client machine to your server. This will be the first in a series of uploading files videos.

Caption and Translate

    Sign In/Register for Dotsub to translate this video.