Let's Start Coding a Upload Image Feature!
Image uploading often seems to be a little difficult for some new developers, but once you understand what ASP.NET offers as part of it’s toolbox, and learn how to read the properties of these specific tools, uploading becomes very easy.
This article will demonstrate how you can upload an image under an “Uploads / Bio" directory. And if the Bio directory is not there, how to create it while uploading an image.
Below are a few steps you will need to follow.
Step 1. Open up your ASPX or ASCX page and drag the “File Upload" component from your toolbox in Visual Studio.Net and name it fldUpload.
Step 2. Drag a button next to the “File Upload" component and label it “Upload" and name it btnUpload.
Step 3. Now double click on the “Upload" button to view the code section / code behind.
Step 4. Make sure your code is using the IO library. If not, modify the top of the code where you have using System and include using System.IO.
Step 5. Write this code within btnUpload_Click event.
string strImage = ""; //this will hold the image name
strImage = fldUpload.FileName.ToString();
fldUpload.SaveAs(Server.MapPath("/uploads/bio/" + fldUpload.FileName.ToString());
That's all. Your website is now ready to accept images. Now let me explain each of the steps above in more detail.
Steps 1 & 2 above show you how to use components that are part of Visual Studio.Net 2005 so it is easy for you to include these components into your website. Each component comes with its own properties which we (programmers / developers) can access. For example .HasFile has one property of the “File Upload" component which we use in Step 5.
Steps 3 & 4 prepare us to start doing some coding. We need to make sure that we are using the System.IO library as it is important for us to be able to upload files or create directories as we will do in Step 5.
Step 5 above shows us how to write the code that can upload an image. We start by creating a string variable called strImage. This variable will hold the name of the image coming from the fldUpload component. Then we check to see if the “bio" directory is under the “uploads" directory. Please note, the “upload" directory needs to be there. This code will not create the “upload" directory.
If the "bio" directory is not there, this code will create it under the “uploads" directory. Next we check to see if there are any files selected by the user. This is accomplished by checking the HasFile property of our component fldUpload. If there is a file, HasFile will return “true" and we can continue to upload the file.
SaveAs is a method of our component fldUpload which we can access to upload the file selected by the user.
As you have seen, with a little bit of coding, uploading files and images can be very easy.