0

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 class="form-control" 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

1 Answer 1

1

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

formData.append("file", fImage.files[0], new_name);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.