Asp.NET Uploading Files to Server

FileUpload Object - Using Server.MapPath

The FileUpload object is used to allow users to upload files to the server. For this, first of all, writing permission must be given to the folder where the file will be saved on the server. When you enter the Plesk panel and click on Permissions from the menu opposite the relevant folder in the Files menu, you can change the settings related to the writing permission in the window that appears.

Before giving the command to upload the file, it is useful to check whether any file is selected from the FileUpload object.

In the example below, it is checked whether a file is selected or not using HasFile property of the FileUpload1 object. If the file is not selected, no action may be taken or an error message may be given.

Then, with the SaveAs method of the FileUpload class, the place where the file will be saved is specified. The Server.MapPath method here also allows us to specify the location on the server.

In the example, the file is saved in the uploads folder with the original (selected file name) name .

if (FileUpload1.HasFile == true)
{
   FileUpload1.SaveAs(Server.MapPath("~/uploads/" + FileUpload1.FileName));
}

Uploading Multiple Files with FileUpload Object

When we change the AllowMultiple property of the FileUpload object to true, we allow multiple files to be selected.

The PostedFiles feature gives us the selected files as a collection. This makes our job extremely easy. Using a loop, we can do what we did for a single file above for all files in the collection.

if (FileUpload1.HasFile)
  {
      string nextFile;
 
      for (int k = 0; k < FileUpload1.PostedFiles.Count; k++)
        {
           nextFile = FileUpload1.PostedFiles[k].FileName;
 
           FileUpload1.PostedFiles[k].SaveAs(Server.MapPath(@"~\uploads\" + nextFile));
 
       }
   }

 

asp.net file upload, fileupload object usage tutorials, using server.mappath, server.mappath file upload to server, fileupload multiple file upload, file upload to server with code, allowmultiple feature

EXERCISES

There are no examples related to this subject.



COMMENTS




Read 780 times.

Online Users: 819



uploading-files-to-server-in-asp-net