45

I need to build a custom file uploader to upload a image profile but I don't want to use the original design of input file but hide it and show a button only to upload the picture.

And I know how to trigger the input file when a different button is clicked with jQuery and with AngularJS but I cannot find the way to do the same with VueJS, do you have any idea?

Kind regards!

1

2 Answers 2

122

Vue style

This might be easier

<input type="file" ref="file" style="display: none" />
<button @click="$refs.file.click()">open file dialog</button>

If more is needed then $refs.file.$el should pointing to the DOM element. Here are the Properties and Methods that you can use.

7
  • This is the better solution as it uses the 'vue way' to do it and is not a workaround at all...
    – Larzan
    Feb 14, 2019 at 17:31
  • 3
    This should be $refs.file.$el.click() Jun 9, 2019 at 1:53
  • @alexandernst why? Jan 25, 2020 at 15:59
  • 1
    @iOSCalendarpatchthecode.com because file isn't pointing to the DOM element. file.$el is what you need. Jan 26, 2020 at 10:17
  • 2
    @alexandernst This doesn't seem to work in vue 3. Jun 4, 2022 at 8:55
10

This is a quick, simple and dirty solution, but it works for me. Create a regular HTML file input, hide it with CSS, or with VueJS. Add a v-on:change event to the hidden file input.

<input id="fileInput" type="file" style="display:none" v-on:change="yourVueMethod()"/>

Create a button that will trigger the click event of the input field.

<button id="fileInputButton" onclick="document.getElementById('fileInput').click()">Open File</button>

And you can now do whatever you want in your method, just as normally. May not be the best solution, but easy to do.

3
  • 1
    This solution might not be supported in some browsers. We tried to do this and in some browsers it did not respond to the click. An alternative solution I've seen is to put your button (the one you like) and put on top the input file control and then change the opacity to 0 (via CSS). Button still there and responds to click, but to the user, it seems like you are clicking on another button. Jan 18, 2017 at 17:12
  • You might want to add $event to the attribute so you get the event as argument in your handler: v-on:change="yourVueMethod($event) Feb 27, 2017 at 13:03
  • 1
    You can't use document.getElementById with vue because it uses virtual dom
    – Dazzle
    Feb 18, 2019 at 17:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.