javascript - 文件上传后VUE JS预览图像重置不起作用
问题描述
当使用文件输入选择图像时,我的图像预览工作。然后我上传图像并重置预览图像和输入文件字段,因为它们需要在文件上传后重置。然后当我选择另一个图像时,该图像的预览不起作用。我正在做的是将其绑定到的变量图像 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]);
}
},
解决方案
input
问题出在下一段代码中 - 当您在 jQuery 克隆的帮助下清理时,您会丢失该元素的所有事件绑定,并且previewImage
不再调用该方法:
// reset the file input to null
var input = $("#file");
input.replaceWith(input.val('').clone(true));
所以尝试vue.js
不使用 jQuery 的方法:
this.$refs.file.value = '';
推荐阅读
- javascript - 使用对象分配和映射问题防止原始数据发生突变
- sql - 显示在“IT”和“SE”工作的每个员工的姓名
- javascript - 行方向填充剩余空间反应原生
- c - 链表中的分段错误
- scheme - 数量不匹配;预期的参数数量与预期的给定数量不匹配:1 给定:2
- c# - 从 AvalonDock LayoutAnchorable 中移除停靠组合按钮
- vue.js - 从 Capacitor 配置文件中获取 appId
- mule - 为组件中的参数“资源”找到无效配置
- c++ - Visual Studio Code - 更改编译器会出错
- wordpress - 使用 url 重写规则防止管理目录重定向