ueno-img_upload
v1.0.1
Published
图片上传组件
Downloads
3
Readme
图片上传组件(基于 react、ts、ant design)
下载依赖
npm i antd
使用方法
- 传入 props
- 组件功能
- 限制上传图片数量(目前支持一张)可扩展限制数量
- 当前是通过获取上传路径,将文件手动上传至指定路径
- 可通过直接指定上传地址上传图片,不必通过接口请求要上传的地址
- props 传入 disabled 可以禁止编辑图片
- 修改组件配置内容
- AdminController.getUrl 应为 自定义的请求, 通过文件名得到将要上传文件的地址
- 组件重要代码
/* * @Description: * @Author: PhilRandWu * @Github: https://github/PhilRandWu * @Date: 2022-11-19 08:31:13 * @LastEditTime: 2023-01-05 23:23:32 * @LastEditors: PhilRandWu */ import { PlusOutlined } from "@ant-design/icons"; import AdminController from "@services/admin"; import { IDataResponse, IErrorDataResponse } from "@services/types/response-type"; import { message, Modal, Upload, UploadFile } from "antd"; import axios from "axios"; import React, { useState } from "react"; export interface ImgUploadInterface { culImgUrl?: string; uploadText?: string; onChange: (newVal: string) => void; disabled?: boolean; } const ImgUpload = (props: ImgUploadInterface) => { const [previewOpen, setPreviewOpen] = useState(false); const getUploadContent = () => { if (props.culImgUrl) { return null; } else { return ( <div> <PlusOutlined /> <div style={{ marginTop: 8 }}>{props?.uploadText ? props?.uploadText : '选择图片'}</div> </div> ) } } const getFileList: () => UploadFile[] = () => { if (props.culImgUrl) { return [ { uid: props.culImgUrl, name: props.culImgUrl, url: props.culImgUrl, } ] } return []; } const handleRequest = async p => { const formData = new FormData(); formData.append(p.file?.name, p.file); const { faceUrl } = await AdminController.getUrl(p?.file?.name); const requestUrl = faceUrl?.split('?')[0]; const result: any = { method: 'put', url: requestUrl, data: p?.file } axios(result).then(res => { if(res?.status === 200) { props.onChange(requestUrl) } }) } return <> <Upload action="/api/upload/movie" // name="imageFile" accept=".jpg,.png,.gif,.webp,.jpeg" listType="picture-card" fileList={getFileList()} disabled={props?.disabled} customRequest={handleRequest} onRemove={() => { if(props?.disabled) { return false; } else { props.onChange(''); } }} onPreview={() => { setPreviewOpen(true); }} > {getUploadContent()} </Upload> <Modal open={previewOpen} title="预览" footer={null} onCancel={() => { setPreviewOpen(false) }}> <img alt="example" style={{ width: '100%' }} src={props.culImgUrl} /> </Modal> </> } export default ImgUpload;
- 父组件基础使用
const Demo = () => { return ( <ImgUpload /> ) } export default Demo;