Don't overwrite file uploaded through FileUplo

2019-06-17 06:29发布

With the following code:

    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string fileExt =
               System.IO.Path.GetExtension(FileUpload1.FileName);

            if (fileExt == ".jpg" || fileExt == ".jpeg" || fileExt == ".gif" || fileExt == ".png")
            {
                try
                {
                    FileUpload1.SaveAs(Server.MapPath("../uploads/originals/" + FileUpload1.FileName));
                    Label1.Text = "File name: " +
                        FileUpload1.PostedFile.FileName + "<br>" +
                        FileUpload1.PostedFile.ContentLength + " kb<br>" +
                        "Content type: " +
                        FileUpload1.PostedFile.ContentType;
                }
                catch (Exception ex)
                {
                    Label1.Text = "ERROR: " + ex.Message.ToString();
                }
            }
            else
            {
                Label1.Text = "Only image files are allowed!";
            }
        }
        else
        {
            Label1.Text = "You have not specified a file.";
        }


    }

I want to make it so that if the file exists it changes the name of it, is there any built in functionality for this? Classic ASP had a parameter so that when you upload say house.jpg, and then again it would become house(1).jpg etc etc which was useful.

6条回答
唯我独甜
2楼-- · 2019-06-17 06:37

There is nothing built in - you will need to make your own algorithm:

string path = Server.MapPath("../uploads/originals/" + FileUpload1.FileName);

if(!File.Exists(path))
{
  FileUpload1.SaveAs(path);
}
else
{
  // figure a different file name, perhaps check for existence as well
}

This can be constructed as a loop as well:

string path = Server.MapPath("../uploads/originals/" + FileUpload1.FileName);

while(File.Exists(path))
{
  // GetAlternatePath generates a new filename based on the path passed in
  path = GetAlternatePath(path); 
}
FileUpload1.SaveAs(path);
查看更多
霸刀☆藐视天下
3楼-- · 2019-06-17 06:43
var fileName = file.FileName;
var extension = Path.GetExtension(fileName);
var nameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);

var i = 1;
while (File.Exists(uploadFolder + fileName))
{
    fileName = nameWithoutExtension.Trim() + " (" + i + ")" + extension;
    i++;
}

file.SaveAs(uploadFolder + fileName);
查看更多
冷血范
4楼-- · 2019-06-17 06:51

I recommend you to tag the Filename with GUID to ensure that each file has unique names.

Maintain the database with the original file name and replace it when the file is downloaded.

查看更多
我只想做你的唯一
5楼-- · 2019-06-17 06:52

You can check if the file exists by using the File static class:

bool exists = System.IO.File.Exists(fileName);

There is no built-in method for adding a (1) to the file name, but you can use the System.IO.Path.GetRandomFileName method to get a file name that is guaranteed to be unique.If you don't need the file name itself to be readable then this might be useful.

查看更多
劳资没心,怎么记你
6楼-- · 2019-06-17 06:57

I have a small method that I use to get unique filenames like that, by adding (1), (2) etc on them:

public static string GetUniqueFilename(string folder, string postedFileName)
{
    string fileExtension = postedFileName.Substring(postedFileName.LastIndexOf('.') + 1);
    int index = 2;

    while (File.Exists(string.Format("{0}/{1}", folder, postedFileName)))
    {
        if (index == 2)
            postedFileName =
                string.Format("{0} ({1}).{2}",
                              postedFileName.Substring(0, postedFileName.LastIndexOf('.')),
                              index,
                              fileExtension);
        else
            postedFileName =
                string.Format("{0} ({1}).{2}",
                              postedFileName.Substring(0, postedFileName.LastIndexOf(' ')),
                              index,
                              fileExtension);
        index++;
    }

    return postedFileName;
}
查看更多
来,给爷笑一个
7楼-- · 2019-06-17 07:00

Why don't you delete the file first if the file is exists and then invoke the "SaveAs" method?

查看更多
登录 后发表回答