0

My goal is to upload multiple files from a Vue.js frontend to a php/Laravel backend.

This is where I collect the files:

<input id="cover-file" @change="onCoverSelected" type="file" multiple>

This is the onCoverSelected method:

  onCoverSelected(e) {
    let files = e.target.files;
    // let fileArray = Object.values(files);
    for (var i = 0; i < files.length; i++) {
      console.log(files[1]);
      this.covers.push(files[1]);
    }
  },

When I console.log the files, they appear as actual files in the DevTools console. So far so good.

However, when I push the files to an array, they become strings! I don't understand why. My backend depends on receiving an array of file objects.

This is a screenshot from DevTools where it shows that the File object becomes a string

img

This is from my backend where I hope to receive an array of File objects, however, I receive an empty array when I dd the covers variable:

$covers = (array)json_decode($request->input('covers'));
dd($covers);

not using the (array) prints the below:

"[object File],[object File],[object File]"

How can I receive an array of File objects in the backend? Thank you.

1 Answer 1

1

Unfortunately, File is an object, representing the binary information of a file. The issue isn't pushing them into an array, the issue is when you convert it to JSON: it will attempt to convert the File object to a string. In this case, it can't represent binary as a string, so File is simply converted to => [object File].

Your 2 options are:

  1. Submit POST data in a multipart form.

  2. Convert the File to a base64 string, or other similar methods. (Can drastically effect performance, encoding and then decoding on server side)

See another related thread here.

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.