当使用文件输入选择图像时,我可以使用图像预览。然后,我上传图像,并重置预览图像和输入文件字段,因为上传文件后需要重置它们。然后,当我选择另一张图像时,该图像的预览不起作用。我正在做的是将其绑定的变量src设置为“”。
以下是上传功能
upload: function(){
//Initialize the form data
let formData = new FormData();
//Add the form data we need to submit
formData.append('file', this.imagefile);
formData.append('journal_id', this.$route.params.id);
//Make the request to the POST /single-file URL
axios.post('/journal_charts/upload', formData)
.then(response => {
console.log('SUCCESS!');
//reset the file input to null
var input = $("#file");
input.replaceWith(input.val('').clone(true));
** //reset the preview image to ''. This basically removes the image tag completely
this.imageData = ''; **
this.callGetChartList(this.$route.params.id);
})
以下是HTML表单。您可以在上传功能中看到正在重置的v-bind:src =“ imageData”。图片预览HTML只是在上传后消失
<input type="file" id="file" ref="file" name="file" class="btn-file"
@change="previewImage" accept="image/*">
<div class="image-preview row" v-if="imageData.length > 0">
<div class="img-wrapper">
<img class="image ml-md-3" v-bind:src="imageData">
</div>
</div>
<div class="row">
<button class="ml-md-3" @click="upload">Upload Chart</button>
</div>
预览图像功能
previewImage: function(event) {
// Reference to the DOM input element
var input = event.target;
// Ensure that you have a file before attempting to read it
if (input.files && input.files[0]) {
// create a new FileReader to read this image and convert to base64 format
var reader = new FileReader();
// Define a callback function to run, when FileReader finishes
its job
reader.onload = (e) => {
// Note: arrow function used here, so that "this.imageData"
refers to the imageData of Vue component
// Read image as base64 and set to imageData
this.imageData = e.target.result;
this.imagefile = input.files[0];
}
// Start the reader job - read file as a data url (base64 format)
reader.readAsDataURL(input.files[0]);
}
},
答案 0 :(得分:0)
问题出在下一段代码中-当您在jQuery克隆的帮助下清理input
时,您将丢失该元素的所有事件绑定以及previewImage
方法不再被调用:
// reset the file input to null
var input = $("#file");
input.replaceWith(input.val('').clone(true));
因此,尝试使用vue.js
而不使用jQuery的方式:
this.$refs.file.value = '';