Home > Enterprise >  Javscript upload rename file on upload with ajax and php
Javscript upload rename file on upload with ajax and php

Time:09-05

This question has been asked many times, but I can't find the right answer.

I'm trying to upload a file with javascript, ajax and php. Which works so far. However, I would like to rename the file when uploading and in javascript, so that I can determine the name of the file from there.

my function to upload the file via ajax in javascript

async function uploadFile() {
  let formData = new FormData();           
  formData.append("file", fImage.files[0]);
  await fetch('/upload.php', {
    method: "POST", 
    body: formData
  });    
  alert('The file has been uploaded successfully.');
}

my input field in html

<input  type="file" id="fImage">

my upload.php

<?php

/* Get the name of the uploaded file */
$filename = $_FILES['file']['name'];

/* Choose where to save the uploaded file */
$location = "upload/".$filename;

/* Save the uploaded file to the local filesystem */
if ( move_uploaded_file($_FILES['file']['tmp_name'], $location) ) { 
  echo 'Success'; 
} else { 
  echo 'Failure'; 
}

?>

The aim would be to determine the file name via javascript, e.g. via a variable

CodePudding user response:

you can use the 3rd parameter of append to specify the filename (MDN)

formData.append("file", fImage.files[0], new_name);
  • Related