Browse Source

添加图片压缩

main
mac 4 months ago
parent
commit
3dea0b0981
  1. 1
      package.json
  2. 9
      src/http/api.ts
  3. 3
      src/http/service.ts
  4. 181
      src/pages/deposit/index.tsx
  5. 23
      src/styles/home.scss
  6. 12
      yarn.lock

1
package.json

@ -12,6 +12,7 @@
"@types/react-dom": "^18.0.0", "@types/react-dom": "^18.0.0",
"antd": "^5.18.1", "antd": "^5.18.1",
"axios": "^1.7.2", "axios": "^1.7.2",
"browser-image-compression": "^2.0.2",
"echarts": "^5.5.0", "echarts": "^5.5.0",
"echarts-for-react": "^3.0.2", "echarts-for-react": "^3.0.2",
"i18next": "^23.11.5", "i18next": "^23.11.5",

9
src/http/api.ts

@ -49,3 +49,12 @@ export const http_submit = (data: HttpRequestPs.Submit) => request({ url: '/v1/s
export const http_notify = () => request({ url: '/v1/message' }) export const http_notify = () => request({ url: '/v1/message' })
export const http_upload = (data:File) => {
const body = new FormData()
body.append('file',data)
return request({
url: '/v1/uploadImg',
data: body,
});
};

3
src/http/service.ts

@ -23,6 +23,9 @@ service.interceptors.request.use(
(config.headers as any).sign = sign; (config.headers as any).sign = sign;
(config.headers as any).timestamp = timestamp; (config.headers as any).timestamp = timestamp;
(config.headers as any).Token = store.state.token; (config.headers as any).Token = store.state.token;
if (config.data instanceof FormData) return config;
if (config.data) { if (config.data) {
config.data = JSON.stringify(config.data); config.data = JSON.stringify(config.data);
} }

181
src/pages/deposit/index.tsx

@ -1,32 +1,40 @@
import { Button, Form, Input, QRCode, Select, Tag, Upload, notification } from 'antd'
import { Button, Divider, Form, Image, Input, Modal, QRCode, Select, Tag, Upload, notification } from 'antd'
import '../../styles/home.scss' import '../../styles/home.scss'
import { http_depositAddress, http_transferDeposit } from '../../http/api'
import { http_depositAddress, http_transferDeposit, http_upload } from '../../http/api'
import { useEffect, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { observer } from 'mobx-react' import { observer } from 'mobx-react'
import store from '../../store' import store from '../../store'
import { copy } from '../../utils' import { copy } from '../../utils'
import signGenerator from '../../http/sign'
import imageCompression from 'browser-image-compression';
const Deposit = () => { const Deposit = () => {
const { userInfo, token } = store.state const { userInfo, token } = store.state
const [form] = Form.useForm() const [form] = Form.useForm()
const [receiveAdds, setReceiveAdds] = useState([] as any)
const [visibles, setVisibles] = useState(false)
const [urls, setUrls] = useState([] as any)
const amount = useRef('0')
const [receiveAdds, setReceiveAdds] = useState([])
const [visibles, setVisibles] = useState([] as boolean[])
const [urls, setUrls] = useState([] as (File | null)[])
const amount = useRef([] as string[])
const [imgUrl, setImgUrl] = useState([] as string[])
const fileRef = useRef<HTMLInputElement>(null)
let [loading, setLoading] = useState([] as any)
const getData = async () => { const getData = async () => {
const res: any = await http_depositAddress() const res: any = await http_depositAddress()
if (res.code === 0) { if (res.code === 0) {
setReceiveAdds(res.data) setReceiveAdds(res.data)
setLoading(res.data.map((_: any) => false))
setVisibles(res.data.map((_: any) => false))
amount.current = res.data.map((_: any) => '0')
} }
} }
const onFinish = (values: any) => {
amount.current = values.amount;
const onFinish = (values: any, index: number) => {
amount.current[index] = values.amount;
visibles[index] = true
setVisibles([...visibles])
form.resetFields() form.resetFields()
setVisibles(true)
} }
const validateAmount = (_: any, value: string) => { const validateAmount = (_: any, value: string) => {
@ -39,79 +47,85 @@ const Deposit = () => {
return Promise.resolve(); return Promise.resolve();
} }
const uploadProps = {
name: 'file',
action: `${process.env.REACT_APP_BASEURL}/api/v1/uploadImg`,
headers: {
sign: signGenerator({
uri: '/api/v1/uploadImg',
timestamp: Date.now(),
args: '',
}),
Token: token,
timestamp: Date.now() as any
},
const fileToBase64 = (file: File) => {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
} }
const onChange = (info: any, index: number) => {
if (info.file.status === 'removed') {
urls[index] && urls.splice(index, 1)
}
const submit = async (index: number) => {
const file = urls[index]
if (!file) return notification.warning({ message: '请上传付款凭证' });
try {
loading[index] = true
setLoading([...loading])
const compressedFile = await imageCompression(file, {
maxSizeMB: 0.5,
maxWidthOrHeight: 1080,
useWebWorker: true,
initialQuality: 1
});
if (info.file.status === 'done') {
if (info.file.response && info.file.response.code === 0) {
urls[index] = info.file.response.data.url
setUrls([...urls])
const result: any = await http_upload(compressedFile)
if (result.code === 0) {
const res: any = await http_transferDeposit({
url: result.data.url,
amount: amount.current[index]
})
loading[index] = false
setLoading([...loading])
if (res.code === 0) {
store.getUserInfo()
urls[index] = null
imgUrl[index] = ''
visibles[index] = false
setVisibles([...visibles])
notification.success({
message: '提交成功'
})
}
} }
notification.success({
message: `凭证上传成功`
});
} else if (info.file.status === 'error') {
notification.error({
message: `凭证上传失败`
});
}
}
const submit = async (index: number) => {
const url = urls[index]
if (!url) return notification.warning({ message: '请上传付款凭证' });
const res: any = await http_transferDeposit({
url,
amount: amount.current
})
if (res.code === 0) {
resetData()
setVisibles(false)
notification.success({
message: '提交成功'
})
} catch (error) {
loading[index] = false
setLoading([...loading])
} }
} }
const resetData = () => {
setUrls([])
amount.current = '0'
const onChange = async (fileList: FileList | null, index: number) => {
try {
if (fileList && fileList.length > 0) {
urls[index] = fileList[0]
console.log('当前文件大小', fileList[0].size / 1024 / 1024);
setUrls([...urls])
fileToBase64(fileList[0]).then((res: any) => {
if (res) {
imgUrl[index] = res
setImgUrl([...imgUrl])
}
})
}
} catch (error) {
}
} }
useEffect(() => { useEffect(() => {
getData() getData()
}, []) }, [])
useEffect(() => {
if (!visibles) {
resetData()
}
}, [visibles])
return ( return (
<div className="deposit"> <div className="deposit">
<div className='text-white fz-22 mb-2 tp' onClick={() => setVisibles(false)}></div>
<div className='text-white fz-22 mb-2 tp' onClick={() => setVisibles(receiveAdds.map(v => false))}></div>
{ {
!visibles && (
<div className="flex-1 container">
receiveAdds.map((item, index) => !visibles[index] && (
<div className="flex-1 container" key={index}>
<div className='p-2'> <div className='p-2'>
<div className='fz-wb-550'>-</div> <div className='fz-wb-550'>-</div>
<div className='text-sub fz-14 mt-1'></div> <div className='text-sub fz-14 mt-1'></div>
@ -120,7 +134,7 @@ const Deposit = () => {
<div className='p-2'> <div className='p-2'>
<Form <Form
layout="vertical" layout="vertical"
onFinish={onFinish}
onFinish={val => onFinish(val, index)}
form={form} form={form}
> >
<Form.Item label={<span className='fz-wb-550'></span>}> <Form.Item label={<span className='fz-wb-550'></span>}>
@ -137,11 +151,11 @@ const Deposit = () => {
</Form> </Form>
</div> </div>
</div> </div>
)
))
} }
{ {
visibles && receiveAdds.map((item: any, index: number) => (
receiveAdds.map((item: any, index: number) => visibles[index] && (
<div key={item.id} className="flex-1 container mb-2"> <div key={item.id} className="flex-1 container mb-2">
<div className='p-2'> <div className='p-2'>
<div className='fz-wb-550'>-</div> <div className='fz-wb-550'>-</div>
@ -162,16 +176,35 @@ const Deposit = () => {
</div> </div>
<div className='mt-2 row-items'> <div className='mt-2 row-items'>
<div className='fz-14 fz-wb-550 mr-2'></div> <div className='fz-14 fz-wb-550 mr-2'></div>
<Upload
{...uploadProps}
maxCount={1}
onChange={(file: any) => onChange(file, index)}
>
<Button type='primary'></Button>
</Upload>
<input ref={fileRef} type="file" onChange={e => onChange(e.target.files, index)} style={{ display: 'none' }} />
<div className='upload row-center'>
{
imgUrl[index] ? (
<>
<Button type='primary' shape='circle' className='delete fz-10' onClick={() => {
urls[index] = null
imgUrl[index] = ''
fileRef.current!.value = ''
setImgUrl([...imgUrl])
}}></Button>
<Image
style={{ width: '100%' }}
src={imgUrl[index]}
/>
</>
) : (
<div style={{ color: '#c2c6cd' }} className='tac' onClick={() => fileRef.current!.click()}>
<div className='fz-24'>+</div>
<div className='fz-12'></div>
</div>
)
}
</div>
</div> </div>
<div className='row-center mt-4'> <div className='row-center mt-4'>
<Button type='primary' disabled={!urls[index]} onClick={() => submit(index)}></Button>
<Button loading={!!loading[index]} type='primary' disabled={!urls[index]} onClick={() => submit(index)}></Button>
</div> </div>
</div> </div>
</div> </div>

23
src/styles/home.scss

@ -61,6 +61,29 @@
box-shadow: 0 .05rem 0.04rem rgba(8, 5, 3, .03); box-shadow: 0 .05rem 0.04rem rgba(8, 5, 3, .03);
border-radius: 5px; border-radius: 5px;
} }
.upload{
width: 100px;
height: 100px;
border-style: dashed;
border-width: 1px;
border-color: #d2d6dd;
border-radius: 10px;
cursor: pointer;
user-select: none;
overflow: hidden;
position: relative;
.delete{
position: absolute;
top: 0;
right: 0;
z-index: 1;
}
&:active{
opacity: 0.6;
}
}
} }

12
yarn.lock

@ -3308,6 +3308,13 @@ braces@^3.0.3, braces@~3.0.2:
dependencies: dependencies:
fill-range "^7.1.1" fill-range "^7.1.1"
browser-image-compression@^2.0.2:
version "2.0.2"
resolved "https://registry.yarnpkg.com/browser-image-compression/-/browser-image-compression-2.0.2.tgz#4d5ef8882e9e471d6d923715ceb9034499d14eaa"
integrity sha512-pBLlQyUf6yB8SmmngrcOw3EoS4RpQ1BcylI3T9Yqn7+4nrQTXJD4sJDe5ODnJdrvNMaio5OicFo75rDyJD2Ucw==
dependencies:
uzip "0.20201231.0"
browser-process-hrtime@^1.0.0: browser-process-hrtime@^1.0.0:
version "1.0.0" version "1.0.0"
resolved "https://registry.yarnpkg.com/browser-process-hrtime/-/browser-process-hrtime-1.0.0.tgz#3c9b4b7d782c8121e56f10106d84c0d0ffc94626" resolved "https://registry.yarnpkg.com/browser-process-hrtime/-/browser-process-hrtime-1.0.0.tgz#3c9b4b7d782c8121e56f10106d84c0d0ffc94626"
@ -10167,6 +10174,11 @@ uuid@^8.3.2:
resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2" resolved "https://registry.yarnpkg.com/uuid/-/uuid-8.3.2.tgz#80d5b5ced271bb9af6c445f21a1a04c606cefbe2"
integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg== integrity sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==
uzip@0.20201231.0:
version "0.20201231.0"
resolved "https://registry.yarnpkg.com/uzip/-/uzip-0.20201231.0.tgz#9e64b065b9a8ebf26eb7583fe8e77e1d9a15ed14"
integrity sha512-OZeJfZP+R0z9D6TmBgLq2LHzSSptGMGDGigGiEe0pr8UBe/7fdflgHlHBNDASTXB5jnFuxHpNaJywSg8YFeGng==
v8-to-istanbul@^8.1.0: v8-to-istanbul@^8.1.0:
version "8.1.1" version "8.1.1"
resolved "https://registry.yarnpkg.com/v8-to-istanbul/-/v8-to-istanbul-8.1.1.tgz#77b752fd3975e31bbcef938f85e9bd1c7a8d60ed" resolved "https://registry.yarnpkg.com/v8-to-istanbul/-/v8-to-istanbul-8.1.1.tgz#77b752fd3975e31bbcef938f85e9bd1c7a8d60ed"

Loading…
Cancel
Save