展示的样式如下
点击摄像机按钮 --- 弹出图片选择器 -- 弹出图片修改模板 -点击确认保存修改后的图片
Form表单内部的第一项的ui模块 --- 图1
// 页面顶部使用到的数据
const [cropperFile, setCropperFile] = useState<any>();
const [crop, setCrop] = useState<any>();
// form内部项
<Form.Item label="" valuePropName="fileList" getValueFromEvent={normFile}>
{/* Spin 头像展示样式 如图1 */}
<Spin spinning={loading}>
<div className={styles.agentAvatar}>
<img
src={getImageUrl(head)}
onError={(e) => {
getDefaultAvatar(e);
}}
alt=""
/>
</div>
</Spin>
{/* 头像上传按钮部分 */}
<div className={styles.uploadBtn}>
{/* 借用 antd 的Upload进行上传 */}
<Upload
accept="image/*" // 接受文件类型为图片
onChange={handleChange} // 上传时的修改方法
multiple={false} // 非多选
showUploadList={false} // 自带的上传列表
// --- 重点 上传前的操作
beforeUpload={(file: any) => {
return new Promise((resolve) => {
setCropperFile(file);
setCrop({
crop: (cropData: any) => {
resolve(cropData);
setCropperVisible(false);
},
});
setCropperVisible(true);
});
}}
customRequest={(options:any) => uploadAws3(options, dispatch)} // 自定义上传,上传到AWS3上 可以改成自己后端的接口
>
{/* 头像上传按钮 如图1的照相机图片 */}
<div className={styles.uploadBtnImg}>
<img src={cameraImg} alt="" />
</div>
</Upload>
</div>
</Form.Item>
// 页面底部 引用弹窗裁剪组件
// cropperVisible ---- 弹窗是否显示
{cropperVisible && (
<CropperModal
visible={cropperVisible}
baseFile={cropperFile}
onCancel={() => {
setCropperVisible(false);
}}
crop={crop}
isMobile={false}
/>
)}
遮罩层的组件封装 可直接去掉注释复制使用
import React, { useEffect, useRef, useState } from 'react';
import Cropper from 'react-cropper'; // 需要装包
import { Modal } from 'antd'; // 使用弹出层样式
import 'cropperjs/dist/cropper.css'; // 引入原始的css
interface CropperModalProps {
visible: boolean;
isMobile: boolean;
onCancel: () => void;
baseFile: any;
crop: any;
}
const CropperModal: React.FC<CropperModalProps> = (props) => {
const { visible, onCancel, isMobile, crop, baseFile } = props;
const cropperRef: any = useRef(null);
const [imageUrl, setImageUrl] = useState('');
useEffect(() => {
fileToUrl();
});
const canStart = () => {
return baseFile instanceof Blob;
};
const urlTofile = () => {
const imageElement: any = cropperRef?.current;
const cropper: any = imageElement?.cropper;
cropper.getCroppedCanvas().toBlob((blob: any) => {
crop?.crop?.(blob);
}, baseFile.type);
};
const fileToUrl = () => {
if (!canStart()) return;
const fileReader: any = new FileReader();
fileReader.onload = () => {
setImageUrl(fileReader.result);
};
fileReader.readAsDataURL(baseFile);
};
return (
// 弹出层的样式
<Modal
maskClosable={false}
visible={visible}
okText="ok"
cancelText="cancel"
onOk={urlTofile}
onCancel={onCancel}
closable={false}
style={{ textAlign: 'center', width: '360px' }}
className="modal-wrap"
>
// 遮罩层的样式
<Cropper
ref={cropperRef}
src={imageUrl}
style={{ height: isMobile ? 300 : 420, width: '100%' }}
aspectRatio={1}
guides={false}
/>
</Modal>
);
};
export default CropperModal;
上传图片到AWS3 的封装方法 如果是上传到后端提供网址 此方法可以忽略
import ServerConfig from '@/utils/request'; // 存放项目的AWS3相关信息
import S3 from 'react-aws-s3'; // 装包
// 自己项目组的aws的相关配置
const config = {
bucketName: ServerConfig.uploadBucketName,
region: ServerConfig.uploadRegion,
accessKeyId: ServerConfig.uploadAccessKeyId,
secretAccessKey: ServerConfig.uploadSecretAccessKey,
};
const ReactS3Client = new S3(config);
/**
* uploadAws
* @param options file onSuccess
* @param dispatch react hook
*/
export const uploadAws3 = (
options: any,
dispatch: any,
) => {
const { file, onSuccess } = options;
const { name } = file;
/**
* Monitor upload progress
* @param progressEvent
*/
const onProgress = (progressEvent: { loaded: number; total: number }) => {
const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
// 是否上传中
dispatch({
type: 'chat/changeIsUploading',
payload: {
isUploading: true,
},
});
// 上传进度 百分比的方法
dispatch({
type: 'chat/changeUploadPercent',
payload: {
uploadPercent: percentCompleted,
},
});
};
ReactS3Client.uploadFile(file, onProgress)
.then((res) => {
// 获取到上传所需要的信息
dispatch({
type: 'upload/changeUploadFileUrl',
payload: {
fileKey: res.key,
fileUrl: res.location,
fileName: name,
},
});
// 成功后的回调
onSuccess(res, file);
})
.catch((err: any) => console.error(err));
};