简体   繁体   English

如何使用asp.net FileUpload控件存储具有相同签名但包含不同数据的文件

[英]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. 我正在使用ASP.NET FileUpload控件将文件上传到服务器并存储。

In my case, the uploaded file should have a .doc or .docx extension, otherwise it will provide an error message. 就我而言,上载的文件应具有.doc.docx扩展名,否则它将提供错误消息。

   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. 假设我上传了一个包含一些数据的doc文件( test.docx )。 It will successfully be uploaded to the server and saved in the project directory ==> ~/Uploads/ 它将成功上传到服务器并保存在项目目录==> ~/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. 但是问题是,当我再次尝试上传具有相同签名( test.docx )但内容不同的文件时,它成功上传了,但是在项目Uploads目录中,先前的文件将被删除,并且仅显示新文件。 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. 正如Lanorkin所建议的那样,您需要创建一种方法来重命名文件,然后将其保存到目录中。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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