【问题标题】:Change file name of FILE UPLOAD control更改 FILE UPLOAD 控件的文件名
【发布时间】:2014-07-15 07:44:04
【问题描述】:

这是我的代码:

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”并保存。

【问题讨论】:

标签: asp.net


【解决方案1】:

试试这个:

//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;
     } 
   }
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 亲爱的朋友,我想获取文件名作为数据库,例如获取“r_id”字段并替换为主文件名
    猜你喜欢
    • 2013-05-19
    • 2019-08-22
    • 2019-11-09
    • 2014-06-06
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 2015-09-02
    • 2018-03-24
    相关资源
    最近更新 更多