如何在 Vue.js (Element.ui) 中的上传按钮旁边 preview/display 上传图像?

How to preview/display an image after uploading at the side of the upload button in Vue.js (Element.ui)?

上传图片后,我正在处理 displaying/previewing 图片。我正在尝试上传图片,然后拨打 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 代码 --> AJAX/FETCH 调用 API

            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
            });
        },

如何在上传图片后显示或预览 picture/photo 作为头像或其他内容。

据我了解你的问题,你可以在将上传的图像发送到服务器之前预览它。您可以在 input type='file' 上附加一个 @change 事件侦听器来侦听更改事件,然后访问 event.target.files[0] 上传的图片。然后把img标签的src改成上传的图片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;
  }
}