PHP - How to rename uploaded file - Asked By Olusegun A. on 28-Sep-09 01:28 PM

Hello Success Oriented People,

I need your help. I design an uploading form but i want people to be able to give the uploaded file a new name at the point of uploading. The sample is as below.


Browse:    ..................................
Name:  ...............................
         Upload


How do i do it?

re - Web Star replied to Olusegun A. on 28-Sep-09 02:13 PM

u simply use one input control for upload a file and 2nd for enter file name by user and save that file with user specific file name as follows

<input type="File" ID="FileUpload1" runat="server" /><br />
        <br />

<Asp:TextBox id="txtFileName" runat="server"/>

<BR>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click"
         Text="Upload File" />


and in code file put this code in button onclick event

if (FileUpload1.HasFile)
            try
            {
                FileUpload1.SaveAs("C:\\Uploads\\" + txtFileName.Text.ToString());
            }
            catch (Exception ex)
            {
                Label1.Text = "ERROR: " + ex.Message.ToString();
            }
        else
        {
            Label1.Text = "You have not specified a file.";
        }


pradeep joshi replied to Olusegun A. on 11-Jan-11 04:22 AM

      Hi,
     this is the code by which you can change the uploaded file name by user interest
    
      HTML Part
  
     <form method="post"  enctype="multipart/form-data">
      <input id="file" type="file" name="data_file"   /><br>
      <input type="text" name="filename"/><br>
      <input type="submit" name="upload" value="Upload" />
   </form>

     PHP Part

    <?php

    if(isset($_POST['upload']))
    {
     $file_name=$_POST['filename'];   //file name given by user
     $Uresume=$_FILES['data_file']['name'];
     $run = move_uploaded_file($_FILES['data_file']['tmp_name'],"./upload/$file_name"); //file saved in upload folder
      if($run)
         echo "uploaded";
      else
       echo "not uploaded";
     }
    ?>