gpt4 book ai didi

c# - 不要覆盖通过 FileUpload 控件上传的文件

转载 作者:太空狗 更新时间:2023-10-29 19:59:03 25 4
gpt4 key购买 nike

使用以下代码:

    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.";
}


}

我想这样做,如果文件存在,它会更改它的名称,是否有任何内置功能?经典 ASP 有一个参数,因此当您上传 house.jpg 时,它会再次变成 house(1).jpg 等等,这很有用。

最佳答案

没有内置任何东西——你需要自己制作算法:

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
}

这也可以构造为一个循环:

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

关于c# - 不要覆盖通过 FileUpload 控件上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3625304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com