【问题标题】:asp.net fileUpload won't upload same file twiceasp.net fileUpload 不会两次上传相同的文件
【发布时间】:2019-11-30 18:05:55
【问题描述】:

我已经检查了这个问题的几个解决方案,当你第一次上传 a.jpg 时很好,但当你再次上传 a.jpg 时,它就不起作用了。 再次上传 a.jpg 的唯一方法是上传 b.jpg。

我的代码是这样的

 <p>Select file to upload:</p>
    <asp:FileUpload ID="FileUploader" runat="server" Width="1000px" />
 <br />

而服务端代码是这样的

protected void FileUploadButton_Click(object sender, EventArgs e)
    {
        try
        {
            //File upload logic. Returns path of uploaded file
            string filePath = Server.MapPath("~/Files/") + Path.GetFileName(FileUploader.PostedFile.FileName);

            //File save to server. Saves file name as uploaded by user to folder, "Files" on the server
            string path = System.IO.Path.Combine("~/Files/",Path.GetFileName(FileUploader.PostedFile.FileName));

            FileUploader.SaveAs(Server.MapPath(path));

            //Function to insert values in excel sheet to database
            InsertIntoDatabase(filePath)
        }
        catch (Exception Ex)
        {
        }//End try

    }//End FileUpload 

我已经阅读了将 fileUploader 放在更新面板上的解决方案。我还尝试在上传文件后重命名文件。这行得通,但它打破了我的逻辑

【问题讨论】:

  • 似乎您还想将其分支到“更新”类型函数...(如果文件存在,则向用户显示“更新”按钮而不是“上传”...和调用一个单独的函数。)然后您要么先删除文件,要么将存储的路径更新为“a(1).jpg”名称。 (我假设文件已上传,但名称已更改以避免覆盖......)IMO您可能不应该删除该文件。你永远不知道什么时候有人可能想要恢复它。
  • @pcalkins 非常感谢。我考虑过删除文件。就像你说的,他们可能想要恢复。此外,重命名文件时插入中断。那本来可以解决我的问题,但不幸的是,除非上传的文件与您传递给它的文件匹配,否则我的插入逻辑将不会运行(由于要求顺便说一句)
  • 好的,所以也许你应该先重命名现有文件。将名称附加到当前日期时间?
  • @pcalkins 我之前尝试过,但我完全没有按照你的评论去做。谢谢它现在有效。您可以发布您的解决方案以便我接受吗?
  • 如果您发布更新的代码会更好...您可以回答自己的问题。

标签: c# asp.net .net file-upload webforms


【解决方案1】:

感谢 pcalkins,我重新保存了文件,然后服务器认为它不会处理同一个文件

  protected void FileUploadButton_Click(object sender, EventArgs e)
    {
        try
        {
            //File upload logic. Returns path of uploaded file
            string filePath = Server.MapPath("~/Files/") + Path.GetFileName(FileUploader.PostedFile.FileName);

            //File save to server. Saves file name as uploaded by user to folder, "Files" on the server
            string path = System.IO.Path.Combine("~/Files/",Path.GetFileName(FileUploader.PostedFile.FileName));

            string day = DateTime.Now.ToString("ss_mm_hh_dd_MM_yyyy");

            FileUploader.SaveAs(Server.MapPath(path));

            //Function to insert values in excel sheet to database
            InsertIntoDatabase(filePath)

             //Resave file to keep track of uploaded files
            File.Copy(filePath, day + filePath);
            File.Delete(filePath);
        }
        catch (Exception Ex)
        {

        }//End try

    }//End FileUpload 

【讨论】:

  • @pcalkins 谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-17
  • 1970-01-01
  • 2012-06-20
  • 2020-06-08
  • 2013-07-13
  • 1970-01-01
相关资源
最近更新 更多