更改FILE UPLOAD控件的文件名

时间:2014-07-15 07:44:05

标签: asp.net

这是我的代码:

if (FileUpload1.HasFile)
{
    try
    {
        string file_name = Path.GetFileName(FileUpload1.FileName);
        FileUpload1.SaveAs(Server.MapPath("~/FoodImage/1/") + file_name);
        Label1.Text = "File Upload";

    }
    catch(Exception)
    {
        Label1.Text = "Can not Upload File!";

    }
}

该代码浏览例如“logo.jpg”并保存在我的服务器中,但我想要保存更改文件名,例如浏览按钮按下并选择“logo.jpg”并单击打开然后更改主文件名“logo.jpg”到“L1.jpg”并保存。

2 个答案:

答案 0 :(得分:0)

asp:FileUpload呈现为input type="file",但没有该选项。但是,您可以执行此简单的解决方法。也就是说,在FileUpload下方放置一个文本框,并提示用户在那里输入所需的文件名。

答案 1 :(得分:0)

试试这个:

//Check if user has selected a file and the file size is not 0
if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentLength > 0)
{
   //Set the name you want for the file with no file extension
   string newFilename = "L1";

   //Get the file extension of the file being uploaded. 
   string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);

   //Combine the new filename and the extension. You want to make sure it's the same file extension.
   string updatedFilename = newFilename + fileExtension;

   //Set the upload location
   string SaveLocation = Server.MapPath("~/FoodImage/1/");
   bool hasErrors = false;

   try
   {
       //Save the file to location with new filename
       FileUpload1.SaveAs(Path.Combine(SaveLocation + updatedFilename));
       hasErrors = false;
   }
   catch (Exception ex)
   {  
       //Display error if any
       lblUploadStatus.Text = "Error uploading file. " + ex.Message.ToString();
       lblUploadStatus.ForeColor = System.Drawing.Color.Red;
       lblUploadStatus.Visible = true;
       hasErrors = true;
   }
   finally
   {
     //Do something or display success or failure

     if (hasErrors == false)
     {
       lblUploadStatus.Text = "File sucessfully uploaded with new filename: " + updatedFilename;
       lblUploadStatus.ForeColor = System.Drawing.Color.Green;
       lblUploadStatus.Visible = true;
     } 
   }
}