1

I'm trying to upload files using PHP script on the server as the upload handler. It works just fine with a traditional web form like this:

<form action="uploadHandler.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

But when I try to switch to a drag-and-drop form the PHP handler is failing with an undefined index on the name value "fileToUpload". Here is the error message:

PHP Notice: Undefined index: fileToUpload in /home/...../uploadHandler.php on line 10

Line 10 of uploadHandler.php contains this statement: $fileName = $_FILES['fileToUpload']['name'];

I'm still using the name=fileToUpload in my drag and drop form:

<form class="my-form">
    <p>Upload multiple files with the file dialog or by dragging and dropping images onto the dashed region</p>
    <input type="file" id="fileToUpload" name="fileToUpload" onchange="handleFiles(this.files)">
    <label class="button" for="fileElem">Select some files</label>
  </form>

This is the function on the page that contains the drag and drop form that calls the uploadHandler:

function uploadFile(file, i) {
  var url = 'https://xxxxxx/uploadHandler.php'
  var xhr = new XMLHttpRequest()
  var formData = new FormData()
  xhr.open('POST', url, true)
  xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')
  
  formData.append('file', file)
  xhr.send(formData)
}

I tried adding something like formData.append('name', 'fileToUpload') before calling xhr.send, but that didn't seem to help.

What am I missing?

  • `formData.append('file', file, 'fileToUpload_name_here');` is gotten with `$_FILES['file']` not `$_FILES['fileToUpload']`. You still need to `move_uploaded_file` too. https://www.php.net/manual/en/features.file-upload.post-method.php – StackSlave Aug 13 '20 at 23:15

0 Answers0