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'
 }
6
  • Did you add enctype="multipart/form-data" to your form? Commented Feb 5, 2020 at 12:22
  • No, I have to add this? Commented Feb 5, 2020 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 Commented Feb 5, 2020 at 12:51
  • I added to the from tag, also I tried like in this example. still, I got null value. Commented Feb 5, 2020 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. Commented Feb 5, 2020 at 13:10

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.)

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.