See the code: codepen
I want to post the data by form;
There is a add-image button,When I click the button first time and select the image,then show the image info in the page. When I click the button again,then show the two images info in the page.
The problem is: I can't set file value to the <input type='file' />
How to do this?
See the code: codepen
I want to post the data by form;
There is a add-image button,When I click the button first time and select the image,then show the image info in the page. When I click the button again,then show the two images info in the page.
The problem is: I can't set file value to the <input type='file' />
How to do this?
Share Improve this question edited Jan 14, 2016 at 7:13 Song Yongtao asked Jan 14, 2016 at 3:27 Song YongtaoSong Yongtao 8351 gold badge8 silver badges18 bronze badges 1-
By security reasons you can't programatically set the value of a
input type='file'
tag. It is not a Vue issue. – Yerko Palma Commented Jan 14, 2016 at 15:29
1 Answer
Reset to default 5Here's a potential solution forked from your original codepen.
I updated the viewmodel to contain an array of files. The v-for
renders that array and includes a hidden file input for each item (same as in your code). However, unlike your sample, the file input is not model-bound to the file info. Instead, it calls the upload()
method whenever its value is changed. The upload()
method handles updating the underlying file info. With that in place, all the Add Image
link needs to do is push a new object onto the files
array and then trigger the click event on that file's input element (after it gets rendered).
Relevant code below.
Html
<ul>
<li v-for="file in files">
<div class="file_item">
<div class="info">
<strong>{{file.name}}</strong>
<p>{{file.size | kb}}</p>
</div>
</div>
<input id="file-{{$index}}" type="file" accept="image/*" @change="upload(file, $event)" style="display:none">
</li>
</ul>
<div class="value_btn">
<a href="#" v-on:click="addImage" class="add">
<span>Add Image</span>
</a>
</div>
Javascript
var vm = new Vue({
el: "#item",
data: {
files : []
},
methods: {
addImage: function(){
this.files.push({ name: "", size: 0})
this.$nextTick(function () {
var inputId = "file-" + (this.files.length-1);
document.getElementById(inputId).click();
});
},
upload: function(file, e){
var f = e.target.files[0];
file.name = f.name;
file.size = f.size;
}
}
})