Tyler Nichol
Tyler Nichol

Reputation: 655

Posting image to laravel with Axios only passing [object file] as string

I have a react app that is the frontend for a laravel application. I am using a simple image uploader that returns the uploaded file to a post route. In the controller for the post route the request is coming in as a string and not the actual object. see my code.

onUpload = (picture) => {
    this.setState({
        pictures: this.state.pictures.concat(picture),
    });

    var curr = this

    const formData = new FormData();
    formData.append('file',picture)
         console.log(picture[0])

        axios
        .post('/upload-subitem-image', formData, fileHeaders)
        .then(function (response) {

            const data = response.data

                    console.log(data)

        })
        .catch(error => {
            console.log(error);
        })
}

When i console the picture object I get

File {name: "test.png", lastModified: 1553443959805, lastModifiedDate: Sun Mar 24 2019 12:12:39 GMT-0400 (Eastern Daylight Time), webkitRelativePath: "", size: 11695, …}

But after passing it to laravel to try and get the file it returns a string when i try to do this.

 $data = $request->File();

and looks like

{file:{"[object file]"}

Headers look like this:

const fileHeaders = {
'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
'content-type': 'multipart/form-data',
'Accept': 'application/json',
  }  

Upvotes: 0

Views: 2357

Answers (2)

Tyler Nichol
Tyler Nichol

Reputation: 655

Ended up adding some stuff to controller in php.

$data = $request->all();
$file = $data['file'];

Upvotes: 0

jabbany
jabbany

Reputation: 529

Judging from the surrounding code, it looks like you're append-ing an array picture.

The API for FormData expects a File or Blob for file uploads so for an array it just turns it into a string. Since your array only has one item, it becomes [object file].

Try doing picture[0] in the append (And make sure to do proper bounds checks etc.)

Ref: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects#Sending_files_using_a_FormData_object

Upvotes: 2

Related Questions