前端上传图片并回显

一、上传

先将按钮画出来,input 使用 display: none 隐藏,通过点击按钮触发 input

<div class="button" @click="clickUploader">点击上传</div>
<input type="file" style="display: none" ref="uploader" accept="image/*" capture="camera" @change="fileChange" />

注意:capture="camera" 表示只能使用拍照,在移动端可以使用。

二、回显

回显有两种方法,一种是上传到服务器,再将从服务器返回的文件流或图片地址展示出来;另一种是将图片转成 base64 ,再将 base64 展示出来。

base64 回显

clickUploader() {
    
    
    this.$refs.uploader.click();
},
fileChange(e) {
    
    
    const file = e.target.files[0];
    const reader = new FileReader();
    reader.onload = function () {
    
    
        const base64 = reader.result;
        sessionStorage.setItem('picture', base64)
    };
    reader.readAsDataURL(file);
    e.target.value = null; // 清除 input 中的值
},
<template>
    <img :src="picture" alt="">
</template>

<script>
export default {
      
      
    computed: {
      
      
        picture() {
      
      
            return sessionStorage.getItem('picture')
        }
    },
}
</script>

上传至服务器回显

考虑到上传文件是会多次使用的,所以把核心部分抽离出来,单独写到一个文件中。以下代码是用 TypeScript 写的,如使用 JavaScript 开发,去除类型断言即可。

utils/file.ts

import {
    
     upload } from "@/api/file.js";

/**
 * @description 文件上传
 * @param file 文件
 * @returns 接口返回数据
 */
export function fileUpload(file: string | Blob) {
    
    
  const params = new FormData()
  params.append('file', file)
  return new Promise((resolve, reject) => {
    
    
    upload(params)
      .then((res: any) => {
    
    
        resolve(res)
      })
      .catch((err: any) => {
    
    
        reject(err)
      })
  })
}

上传页面

<template>
    <div class="button" @click="clickUploader">点击上传</div>
    <input type="file" style="display: none" ref="uploader" accept="image/*" capture="camera" @change="fileChange" />
</template>

<script>
import {
      
       fileUpload } from '@/utils/file'

const clickUploader = () => {
      
      
    this.$refs.uploader.click();
},
const fileChanger = (e) => {
      
      
    this.fileUpload(e.target.files[0]).then((res) => {
      
      
        sessionStorage.setItem('picture', res.data.url)
    });
    e.target.value = null; // 清除 input 中的值
},
</script>

展示页面

<template>
    <img :src="picture" alt="">
</template>

<script>
export default {
      
      
    computed: {
      
      
        picture() {
      
      
            return sessionStorage.getItem('picture')
        }
    },
}
</script>

END

猜你喜欢

转载自blog.csdn.net/m0_53808238/article/details/131069658
今日推荐