前端上传图片并回显

5 篇文章 0 订阅

一、上传

先将按钮画出来,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

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

温其如玉_zxh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值