【发布时间】:2019-07-28 02:54:53
【问题描述】:
当使用文件输入选择图像时,图像预览工作正常。然后我上传图像并重置预览图像和输入文件字段,因为它们需要在文件上传后重置。然后当我选择另一个图像时,该图像的预览不起作用。我正在做的是将其绑定到的变量图像 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]);
}
},
【问题讨论】:
-
显示
previewImage函数。 -
增加了预览图片功能
标签: javascript vue.js