上传后如何在Vue.jsElement.ui中的上传按钮的侧面预览/显示图像?

问题描述

上传图像后,我正在显示/预览图像。我正在尝试上传图片,然后进行axios / AJAX调用

请在下面找到代码

HTML代码

        <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

Live Demo Here

您也可以通过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;
  }
}