ant-design/components/upload/demo/transform-file.md
章鱼 7fd093bd0a
docs: feat components TS demo (#34742)
* docs: add general components TS demo

* docs: add layout components TS demo

* docs: add navigation components TS demo

* docs: add data entry components TS demo

* chore(deps): add types for qs

* docs: add data display TS demo

* docs: add feedback components TS demo

* docs: add other components TS demo

* chore(deps): add types

* docs: unified demo code style

* docs: fix lint error

* docs: add demo TS type

* docs: fix demo TS type

* test: update snapshot

* docs: fix TS demo

* feat: update Rate character type

* docs: fix lint error

* feat: update Rate character type

* feat: update Rate character type
2022-05-19 09:46:26 +08:00

57 lines
1.4 KiB
Markdown

---
order: 10
title:
zh-CN: 上传前转换文件
en-US: Transform file before request
---
## zh-CN
使用 `beforeUpload` 转换上传的文件(例如添加水印)。
## en-US
Use `beforeUpload` for transform file before request such as add a watermark.
```tsx
import React from 'react';
import { Upload, Button } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
const props: UploadProps = {
action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
listType: 'picture',
beforeUpload(file) {
return new Promise(resolve => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const img = document.createElement('img');
img.src = reader.result as string;
img.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const ctx = canvas.getContext('2d')!;
ctx.drawImage(img, 0, 0);
ctx.fillStyle = 'red';
ctx.textBaseline = 'middle';
ctx.font = '33px Arial';
ctx.fillText('Ant Design', 20, 20);
canvas.toBlob(result => resolve(result as any));
};
};
});
},
};
const App: React.FC = () => (
<Upload {...props}>
<Button icon={<UploadOutlined />}>Upload</Button>
</Upload>
);
export default App;
```