功能演示

我们要实现的功能如下,有两个按钮,点击第一个按钮选择文件,选择文件后点击第二个按钮上传到服务器。

功能需求:

  1. 只允许上传 pngjpg/jpeg 格式的图片

  2. 没有上传图片时显示占位图

  3. 选择完图片后在页面中渲染出来

构建页面

template

<template>
<div>
<div>
<!-- 选择图片后展示待上传的图片 -->
<img v-if="base64img" :src="base64img" />
<!-- ↓ 没有选择时显示占位图 -->
<img v-else="base64img" src="@/assets/placeholderImg.png" />
</div> <!-- 限制最大待上传的文件数量为 1 -->
<!-- 添加选择文件后的回调和移除待上传文件的回调 -->
<a-upload :before-upload="beforeUpload" :max-count="1" @remove="handleRemove">
<a-button>
<upload-outlined></upload-outlined>
Select File
</a-button>
</a-upload>
<!-- 点击上传按钮 -->
<a-button @click="triggerUpload" :loading="btnLoading">上传</a-button>
</div>

逻辑部分

TypeScript

import { UploadOutlined } from '@ant-design/icons-vue'
import fruitApi from "@/api/fruitApi";
import {ref} from "vue";
import {Upload} from "ant-design-vue";
import {Notice} from "@/utils/interfaces"; const fileList = ref();
// ↑ 待上传文件列表 (其实里面也就能放一个文件)
const base64img = ref();
// ↑ 我们在页面中显示待上传的图片的原理是
// 将所选择的本地图片转换为 Base64 编码
// 之后让图片的 src = base64img 来实现的
// 所以 base64img 就是一个储存图片编码的字符串
const btnLoading = ref<boolean>(false);
// ↑ 上传按钮的 loading 状态
// 在点击上传 至 获取服务器回调的时间内 按钮不可用 /**
* 对图片编码的函数
*/
function getBase64(img: Blob, callback: (base64Url: string) => void) {
const reader = new FileReader();
reader.addEventListener('load', () => callback(<string>reader.result));
// ↑ 监听 reader 的 load 事件,触发时执行回调函数
// 回调函数的作用就是将图片编码的base64字符串传给 base64img
reader.readAsDataURL(img);
} /**
* andv 上传文件的回调
* 返回 false 则不会上传文件,而是由我们手动上传
* 返回 Upload.LIST_IGNORE 会取消将文件添加至待上传列表
* @param file 所选择的文件
*/
function beforeUpload(file: any) {
console.log(file);
// 判断文件是否为图片格式
const isImg = (file.type === 'image/jpeg' || file.type === 'image/png'); // 如果文件不是图片格式则禁止上传
if (!isImg) {
Notice.error("只能上传 jpeg/jpg/png 格式的文件!");
// ↑ Notice.error 是我自己写的 Notice 类的一个静态函数
// 用的是 antdv 的 Notifiacation
return Upload.LIST_IGNORE;
}
fileList.value = file;
// ↓ 获取所需要上传图片的 Base64 编码
getBase64(fileList.value, (cb_img: string) => {
// 将获取到的所要上传图片的 Base64 编码渲染到图片上
base64img.value = cb_img;
})
return false;
} /**
* 点击上传按钮的回调
*/
function triggerUpload() {
const formData = new FormData(); // 对文件列表 判空
if (fileList.value != null) {
formData.append("file", fileList.value as any);
} else {
Notice.error("文件不能为空!")
return Upload.LIST_IGNORE;
} // ↓ 在上传过程中,按钮为 loading 状态
btnLoading.value = true; // 请求上传接口
fruitApi({
method: 'put',
url: 'api/upload',
data: formData
})
.then((resp: any) => {
console.log(resp);
if (resp.code === 1) {
Notice.success(<string>resp.data);
changeUploadItemColor("#49aa19");
} else {
Notice.error("上传失败~");
changeUploadItemColor("#ff4d4f");
// ↑ 下面会提到这个函数
}
btnLoading.value = false;
})
.catch((err) => {
console.log(err);
Notice.error("发生了错误~");
btnLoading.value = false;
changeUploadItemColor("#ff4d4f");
})
} /**
* 待上传图片被删除的回调
*/
function handleRemove() {
fileList.value = null;
// ↑ 置空待上传文件列表
base64img.value = null;
// ↑ 显示默认占位图
} /**
* 上传图片成功或失败后 list 变色的函数
*/
type uploadItemColor = "#49aa19" | "#ff4d4f";
// ↑ 两个颜色 绿 和 红
function changeUploadItemColor(color: uploadItemColor) {
const uploadListItem = document.querySelector(".ant-upload-list-item-name");
// ↑ 类名是 antdv 规定的,选择这个类名即可
(uploadListItem as any).style.color = color;
// ↑ 使item文字变色
}

这次真的是把 TypeScript 写成了 anyScript,中间不知道用了多少的类型断言和 :any

End

开头已经展示过页面效果啦,就不再测试了

Ant-Design-Vue 图片上传的更多相关文章

  1. Ant Design Upload 组件上传文件到云服务器 - 七牛云、腾讯云和阿里云的分别实现

    在前端项目中经常遇到上传文件的需求,ant design 作为 react 的前端框架,提供的 upload 组件为上传文件提供了很大的方便,官方提供的各种形式的上传基本上可以覆盖大多数的场景,但是对 ...

  2. vue图片上传组件

    前言:很多项目中都需要用到图片上传功能,而其多处使用的要求,为了避免重复造轮子,让我决定花费一些时间去深入了解,最终封装了一个vue的图片上传组件.现将总结再次,希望有帮助. Layout <d ...

  3. vue 图片上传

    功能说明: 1.调用手机拍照功能 2.调用相册功能 3.图片上传功能 4.图片预览功能 5.图片删除功能 关键点: .input 新增multiple .accept="image/*处理I ...

  4. vue 图片上传功能

    这次做了vue页面的图片上传功能,不带裁剪功能的! 首先是html代码,在input框上添加change事件,如下:   <ul class="clearfix">   ...

  5. vue图片上传的简单组件

    <template> <div class="rili" id="rili"> <div class="updel&qu ...

  6. 保姆级SpringBoot+Vue图片上传到阿里云OSS教程

    小二是新来的实习生,作为技术 leader,我给他安排了一个非常简单的练手任务,把前端 markdown 编辑器里上传的图片保存到服务器端,结果他真的就把图片直接保存到了服务器上,这下可把我气坏了,就 ...

  7. vue图片上传

    之前花了两个月用vue做了一个建筑照片我的webApp,前端就我一人,负责用vue写页面对接接口,后台一个程序员负责写接口,嵌套个安卓ios的壳.搞的是风风火火,过程也是很心累,大多不在技术,在于所谓 ...

  8. vue图片上传到七牛云

    代码: <template> <div class="upload-info"> <div> <el-upload class=" ...

  9. vue图片上传及java存储图片(亲测可用)

    1.前言 在使用elementui的upload组件时,我一直无法做到上传的图片和其他数据一起提交.单纯的上传文件,java的存储图片的方式也有局限性. 我知道的后端保存图片有两种方式:一种是直接存储 ...

  10. 后台管理系统之“图片上传” --vue

    图片上传(基于vue) 相信上传图片是所有系统必备的功能吧,工作中的第一个管理系统就在上传图片的功能上卡顿了一整天. 当时用的elementUI组件,但是由于样式和设计图样式差别较大再加上原生相较好理 ...

随机推荐

  1. pytest批量执行多个测试文件(批量执行一个文件夹下的所有测试用例)

    图片 代码 #!/usr/bin/env python # @File : test_runall.py import pytest import os # path = os.path.dirnam ...

  2. 机器学习:详解什么是端到端的深度学习?(What is end-to-end deep learning?)

    什么是端到端的深度学习? 深度学习中最令人振奋的最新动态之一就是端到端深度学习的兴起,那么端到端学习到底是什么呢?简而言之,以前有一些数据处理系统或者学习系统,它们需要多个阶段的处理.那么端到端深度学 ...

  3. Jmeter函数助手26-logn

    logn函数用于记录一条日志并返回空值. String to be logged (and returned):要打印的字符 Log level (default INFO) or OUT or ER ...

  4. 11、SpringMVC之文件下载和上传

    创建名为spring_mvc_file的新module,过程参考9.1节和9.5节 11.1.文件下载 11.1.1.创建图片目录并放置图片 11.1.2.页面请求示例 <a th:href=& ...

  5. 【郝斌C ST】02

    自学视频<郝斌C语言自学教程> 10: https://www.bilibili.com/video/BV1os411h77o C语言大纲 - 1.简介 - 2.基本编译知识 - 3.数据 ...

  6. 【REGX】正则表达式 选中空白行

    参考地址: https://www.cnblogs.com/peijyStudy/p/13201576.html VScode并列替换不够智能,我需要等行粘贴,结果SHIFT+ALT复制内容粘贴上去就 ...

  7. 【C】Re06 数组与指针

    一.指针和数组 void pointerAndArray() { int array[5] = {1, 2, 3, 4, 5}; printf("pointer array -> %p ...

  8. AI的技术发展:记忆与想象力 —— 【人工智能】记忆、想象与AI | 查兰·兰加纳特 | 心理学与神经科学家 | 人脑如何记忆 | 内部模型 | 稳定可塑性难题 | 想象力的由来 | AI内容传播 | 脑机接口BCI

    原文地址: https://www.youtube.com/watch?v=cHYKbVP1GTQ 加利福尼亚大学戴维斯分校教授.心理学家兼神经科学家查兰·兰加纳特Charan Ranganath,最 ...

  9. 2018年视频,路径规划:层次化路径规划系统——hierarchical pathfinding system —— Hierarchical Dynamic Pathfinding for Large Voxel Worlds (续)

    前文: 2018年视频,路径规划:层次化路径规划系统--hierarchical pathfinding system -- Hierarchical Dynamic Pathfinding for ...

  10. 如何理解自动驾驶的分级:L0、L1、L2、L3、L4、L5

    相关: https://baijiahao.baidu.com/s?id=1792281493472406727&wfr=spider&for=pc L0,就是完全没有自动驾驶技术的车 ...