我写了这个:
protected void btnup_Click(object sender, EventArgs e)
{
if (ASPxUploadControl1.HasFile)
{
try
{
string filename = Path.GetFileName(ASPxUploadControl1.FileName);
ASPxUploadControl1.SaveAs(Server.MapPath("upload/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
问题是,如果我已经有File1.jpg,如果其他人上传File1.jpg,它将覆盖它。
这里做什么?
答案 0 :(得分:5)
这里可以做些什么来使文件名在服务器上唯一,以避免覆盖。
if (ASPxUploadControl1.HasFile)
{
try
{
string extension = Path.GetExtension(ASPxUploadControl1.FileName);
string id = Guid.NewGuid().ToString();
string fileLocation = string.Format("{0}/{1}{2}",
Server.MapPath("upload/"),
id, extension);
ASPxUploadControl1.SaveAs( fileLocation );
StatusLabel.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. "
+ "The following error occured: " + ex.Message;
}
}
答案 1 :(得分:3)
当您致电ASPxUploadControl1.SaveAs
时,assign是一个唯一名称。例如,内容的运行编号/ GUID / MD5哈希。无论你认为合适。
我发现使用System.Guid.NewGuid().ToString()
答案 2 :(得分:1)
您必须为文件名指定unique
名称
DB序列或静态运行数变量可能适合您。
您可以使用随机唯一GUID字符串,请参阅this MSDN文章
答案 3 :(得分:1)
我建议您在Web应用程序中保存文件时使用Guid以避免此类问题,我通常会使用:
Guid.NewGuid().ToString().Replace("-", "").ToUpper()
表示文件名。
答案 4 :(得分:0)
protected void btnup_Click(object sender, EventArgs e)
{
if (ASPxUploadControl1.HasFile)
{
try
{
string ext = Path.GetExtension(ASPxUploadControl1.FileName);
string filename = DateTime.Now.Ticks.ToString()+ext;
ASPxUploadControl1.SaveAs(Server.MapPath("upload/") + filename);
StatusLabel.Text = "Upload status: File uploaded!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}