4

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?

1
  • By security reasons you can't programatically set the value of a input type='file' tag. It is not a Vue issue. Commented Jan 14, 2016 at 15:29

1 Answer 1

5

Here'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;
    }
  }
})
Sign up to request clarification or add additional context in comments.

Comments

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.