Ant Design Upload listType=“picture-card“ 实现多图上传以及点击预览图片封装

用户可以上传图片并在列表中显示缩略图,当上传照片数到达限制后,上传按钮消失。点击图片打开图片预览弹框。在使用的地方引入组件,组件在传图后会返回图片数组。import React, { useState, useEffect } from 'react';import { Upload, Modal } from 'antd';import { PlusOutlined } from '@ant-design/icons';//上传前判断标准function beforeUpload(file)
摘要由CSDN通过智能技术生成

用户可以上传图片并在列表中显示缩略图,当上传照片数到达限制后,上传按钮消失。点击图片打开图片预览弹框。在使用的地方引入组件,组件在传图后会返回图片数组。

import React, {
    useState, useEffect } from 'react';
import {
    Upload, Modal } from 'antd';
import {
    PlusOutlined } from '@ant-design/icons';

//上传前判断标准
function beforeUpload(file) {
   
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
   
        message.error('只能上传JPG/PNG格式的文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 5;
    if (!isLt2M) {
   
        message.error('图片大小不能超过5M!');
    }
    return isJpgOrPng && isLt2M;
}

const UploadMorePic = (props) => {
   
    const {
   
        action, //上传地址
        headers, //设置上传的请求头部
        maxLength, //最大上传图片数量
        urlList, //已上传的文件列表
        onFinish = () => {
    //上传完回调
            return false;
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
el-upload 是 Element UI 中的一个上传组件,可以方便地上传文件,包括图片。下面是使用 el-upload 手动实现图片上传的步骤: 1. 在页面中引入 el-upload 组件,并设置其属性 action、headers、name 和 list-type。其中,action 是上传文件的地址,headers 是上传请求的头部信息,name 是上传文件的字段名,list-type上传文件列表的类型,可以设置为 text、picture、picture-card 中的一种。 2. 在 data 中定义 fileList 数组,用来保存上传的文件列表。 3. 在 methods 中定义 handleUpload 方法,用来处理上传文件的逻辑。该方法会接收一个参数 file,表示要上传的文件。在该方法中,可以使用 FormData 对象来创建一个表单数据对象,然后将 file 添加到表单数据中,最后发送上传请求。 4. 在 el-upload 组件中添加 ref 属性,并在 handleUpload 方法中使用 this.$refs.upload.upload() 调用上传方法。 下面是一个示例代码: ```html <template> <el-upload ref="upload" action="/api/upload" :headers="headers" :name="name" :list-type="listType" :file-list="fileList" @change="handleUpload"> <el-button>上传图片</el-button> </el-upload> </template> <script> export default { data() { return { headers: { Authorization: 'Bearer ' + localStorage.getItem('token') }, name: 'image', listType: 'picture', fileList: [] } }, methods: { handleUpload(file) { const formData = new FormData() formData.append('file', file.raw) // 发送上传请求 axios.post('/api/upload', formData, { headers: { 'Content-Type': 'multipart/form-data', Authorization: 'Bearer ' + localStorage.getItem('token') } }).then(res => { console.log(res.data) // 上传成功后将文件添加到 fileList 中 this.fileList.push({ name: file.name, url: res.data.url }) }).catch(err => { console.error(err) }) // 手动清空上传文件列表,避免重复上传同一文件时出现问题 this.$refs.upload.clearFiles() } } } </script> ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值