如何解决上传后如何在Vue.jsElement.ui中的上传按钮的侧面预览/显示图像?
上传图像后,我正在显示/预览图像。我正在尝试上传图片,然后进行axios / AJAX调用。
请在下面找到代码:
<span>User Name</span>
<input v-model="person_name" placeholder="Edit Me">
<br>
<!--Uploading pic -->
<span>display Pic</span>
<input type="file" name="file" />
<br>
<!-- I want to display this uploaded pic here,before submitting the form -->
<!-- Skipping the code to submit (button code,etc) the form -->
Javascript代码->对API的AJAX / FETCH调用
var formData = new FormData();
var fileField = document.querySelector("input[type='file']");
formData.append('username',this.person_name);
formData.append('File',fileField.files[0]); // getting the file attached
const body = formData;
const init = {
method: 'POST',body
};
fetch('http://..xyz....com',init)
.then((response) => {
return response.json(); // or .text() or .blob() ...
})
.then((text) => {
// text is the response body
})
.catch((e) => {
// error in e.message
});
},
解决方法
据我所知,您可以预览上传的图像,然后再将其发送到服务器。您可以在@change
上附加一个input type='file'
事件监听器,以监听更改事件,然后访问event.target.files[0]
上传的图像。然后,用已上传的图像src
更改img
标签的src
。
您也可以通过preview()
方法将其上传到服务器后立即发送到服务器,也可以使用upload
按钮将其发送到服务器。
您的Vue模板:
<template>
<div id="app">
<img id="image" :src="imgSrc" />
<input type=file @change="preview">
<div>
<button @click="upload()">Upload</button>
</div>
<div> {{ uploaded }} </div>
</div>
</template>
脚本:
data: () => ({
imgSrc: '',uploaded: ''
}),methods: {
preview(e) {
var pic = document.getElementById('image')
let imgSrc = URL.createObjectURL(e.target.files[0]);
this.imgSrc = imgSrc
},upload() {
this.uploaded = this.imgSrc;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。