0

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',
  }  
Tyler Nichol
  • 635
  • 2
  • 7
  • 28

2 Answers2

2

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

jabbany
  • 539
  • 1
  • 5
  • 10
  • In the right direction but now its empty - {file: {…}} – Tyler Nichol Jun 17 '19 at 18:06
  • Refer to the other posts linked in the comments section, you may need to set the `content-type` properly. – jabbany Jun 17 '19 at 18:08
  • To further debug this, the next step you should do would probably be to inspect the outgoing request (e.g. in the browser networking inspector) and make sure that the post body contains the file data. If it does, then you may need to fix something on the server side. – jabbany Jun 17 '19 at 18:16
  • file: (binary) that is what is coming up as the request now – Tyler Nichol Jun 17 '19 at 18:22
  • That looks like the correct behavior. You'll need to figure out what you want to do with that binary in PHP. – jabbany Jun 17 '19 at 18:24
0

Ended up adding some stuff to controller in php.

$data = $request->all();
$file = $data['file'];
Tyler Nichol
  • 635
  • 2
  • 7
  • 28