好久没更博啦,最近写项目需要实现将签名生成的url(base64图片格式)上传到upload接口。在这简要的记录下~~
背景:1.实现签名功能; 2.上传base64图片(格式自定义)
实现:1.签名功能
引入react-signature-canvas中的SignatureCanvas绘制:
import React, { useState } from 'react';
import SignatureCanvas from 'react-signature-canvas';
const Signature = props => {
const { resetImg } = props;
const [sign, setsign] = useState(null);
const end = () => {
resetImg(sign);
};
return (
<>
<SignatureCanvas
canvasProps={{ width: 1264, height: 400, className: 'sigCanvas' }}
penColor="#181818"
ref={ref => {
setsign(ref);
}}
onEnd={end}
throttle={20}
minWidth={1}
maxWidth={4}
/>
</>
)
};
export default Signature;
在b页面引入signature组件:
import React, { useState } from 'react';
import Signature from '@/pages/Order/FlowPage/components/Signature';
const SignModal = props => {
const [sigPad, setsigPad] = useState(null);
const reset = value => {
setsigPad(value);
dispatch({
type: 'global/save',
payload: {
showSignUrl: value,
},
});
};
const confirm = () => {
setUrl(sigPad.getTrimmedCanvas().toDataURL('image/png'));
props.clickOK(sigPad.getTrimmedCanvas().toDataURL('image/png'));
};
const resetSign = () => {
sigPad && sigPad.clear();
};
return (
<div>
<Modal
visible={props.visible}
title='modal'
width={1296}
onOk={handleOk}
onCancel={handleCancel}
footer={[
<div key="signModal">
<Button onClick={() => handleCancel()}>CANCEL</Button>
<Button type="primary" loading={loading} onClick={() => handleOk()}>OK</Button>
<Button onClick={() => resetSign()} >RESET</Button>
</div>,
]}
>
<Signature resetImg={reset} />
</Modal>
</div>
);
};
export default SignModal;
点击ok如下图所示:
2.上传图片操作:
const submitSign = () => {
// 重要三步骤
const formData = new FormData();
const fileImg = dataURLtoFile(showSignUrl);
formData.append('file', fileImg, `${Date.now()}.png`);
dispatch({
type: 'global/saveSignature',
payload: formData,
}).then(({ success, data, errMessage }) => {
if (success) {
console.log(success)
}).then(({ success, errMessage }) => {
if (success) {
message.error(errMessage);
}
});
}
});
};
Last: 希望能帮到需要的小伙伴们~越努力越幸运