0

I try to create a simple file upload with Vuejs and Laravel. But my 'file' variable it seems to be null on post.

<b-form-group label-for="file">
    <b-form-file
        v-model="file"
        id="file"
        :state="Boolean(file)">
        </b-form-file>
</b-form-group>

data() {
    return {
        file: null,
    },
}

and a method for post . (that works for the rest of the form)

addContract(newContract) {
    post("/contracts/" + `${this.customer_id}`, newContract)
        .then((response) => {
            //
        }
        .catch(error){
            //
        }
}

Controller

//code
    $fileName = time(). '.' .$request->$file->getClientOriginalExtention();
    $request->file->move(public_path('upload'), $fileName);
    dd($fileName);  
//code

UPDATE I set the axios header, but now I got error 422, when it was application I didn't but it still didn't work.

 headers: {
    'Content-Type': 'multipart/form-data'
 }
Beusebiu
  • 1,433
  • 4
  • 23
  • 68
  • Did you add `enctype="multipart/form-data"` to your form? – Remul Feb 05 '20 at 12:22
  • No, I have to add this? – Beusebiu Feb 05 '20 at 12:40
  • Yes you will have to add it, otherwise you won't be able to send files with the post request. See [here](https://stackoverflow.com/a/4526286/9193055) – Remul Feb 05 '20 at 12:51
  • I added to the from tag, also I tried like in this example. still, I got null value. – Beusebiu Feb 05 '20 at 12:58
  • I don't know what your `post()` method does but you probably have to set the `multipart/form-data` as the header in your `post()` method. – Remul Feb 05 '20 at 13:10
  • Ok, now I have, 'Content-Type': 'multipart/form-data' , but the data for file are still null, if I console log before post, file has value. I try to dd from controller method but it didn't get there. – Beusebiu Feb 05 '20 at 13:29

1 Answers1

1

In order for the file to upload via native browser submit, you must provide a name for the file input (along with adding enctype="multipart/form-data" to the enclosing <form> element).

<b-form-file
  v-model="file"
  id="file"
  name="file"
  :state="Boolean(file)">
</b-form-file>

This is the same requirement for any form <input>, <select>, or <textarea> control.

Troy Morehouse
  • 5,320
  • 1
  • 27
  • 38
  • Same output. before put request in console log I got "file: ..." , but in the request "file: {}", and with 'Content-Type': 'multipart/form-data' , I got 422, for validation, but with application pass validation(that is correct, for the rest of the input.) – Beusebiu Feb 06 '20 at 06:35