Search code examples
javascriptfilefetch-apiform-data

Modify items of $_FILES global var in JS before uploading files


Suppose simple file uploading with JS request and PHP processing

For example:

<input type="file" name="items[]">
<button>UPLOAD</button>

<script>
document.querySelector('button').addEventListener('click', (e) => {
    
    let data = new FormData();
    data.append('items[]', document.querySelector('input').files[0]);

    fetch('/upload.php', {
        method: 'POST',
        body: data
    })
    .then(response => response.text())
    .then(text => {
        console.log(text);
    });
});
</script>

Is it possible in JS to somehow modify items[] array that is $_FILES['items'] for example its ['name'] and ['type'] subarrays before sending to PHP?

Something like (doesn't work)

data.append('items[]["name"][0]', 'fake_name.ext');

Solution

  • You cannot change the type property of a File as it is read-only but you can set a custom name as the 3rd parameter to FormData.prototype.append()

    data.append(
      "items[]",
      document.querySelector("input[type=file]")?.files[0],
      "fake_name.ext"
    );
    

    If you really want to change the type, you could copy the original file into a new File and alter the type property in options

    const file = document.querySelector("input[type=file]")?.files[0];
    const copy = new File([file], "fake_name.ext", {
      type: "some/mime-type",
    });
    
    data.append("items[]", copy);