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

124

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.

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

7 Comments

This is the better solution as it uses the 'vue way' to do it and is not a workaround at all...
This should be $refs.file.$el.click()
@alexandernst why?
@iOSCalendarpatchthecode.com because file isn't pointing to the DOM element. file.$el is what you need.
@alexandernst This doesn't seem to work in vue 3.
|
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 Comments

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.
You might want to add $event to the attribute so you get the event as argument in your handler: v-on:change="yourVueMethod($event)
You can't use document.getElementById with vue because it uses virtual dom

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.