简体   繁体   中英

How to store files that have the same signature but contain different data using asp.net FileUpload control

I am using an ASP.NET FileUpload control to upload a file to a server and store it.

In my case, the uploaded file should have a .doc or .docx extension, otherwise it will provide an error message.

   if (fileUpload1.HasFile)
   {
       string fileExtension = Path.GetExtension(fileUpload1.FileName);

       if (fileExtension.ToLower() == ".doc" || fileExtension.ToLower() == ".docx")
       {
              fileUpload1.SaveAs(Server.MapPath("~/Uploads/" + fileUpload1.FileName));
              statusLabel.Text = "File Uploaded Successfully";
              statusLabel.ForeColor = System.Drawing.Color.Green;
       }
       else
       {
              statusLabel.Text = "Only files with .doc or .docx extension are allowed!";
              statusLabel.ForeColor = System.Drawing.Color.Red;
       }
}

When I upload a file and click upload button it will store it on the following directory of my project:

~/Uploads/

Suppose I upload a doc file ( test.docx ) that has some data. It will successfully be uploaded to the server and saved in the project directory ==> ~/Uploads/

But the problem is, when I again try to upload a file with the same signature ( test.docx ) but different contents, it uploads successfully but in the project Uploads directory the previous file will erased and only the newly file will present. But I want to keep both files.

How can I solve this problem?

As Lanorkin suggested you need to create a method to rename the file and then save it into the directory.

So in your code include the method to create a unique name for the file:

var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName).Substring(1); 

fileUpload1.SaveAs(Server.MapPath("~/Uploads/" + Guid.NewGuid().ToString("N") + "." + FileExtension);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM