在使用Ant Design的Upload组件时,如果不提供action
属性,那么文件的上传处理需要通过customRequest
属性来自定义实现。
以下是一个不使用action
属性,而是通过customRequest
实现文件上传的例子:
import React from 'react'; import { Upload, message, Button } from 'antd'; import { UploadOutlined } from '@ant-design/icons'; function beforeUpload(file) { const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'; if (!isJpgOrPng) { message.error('You can only upload JPG/PNG file!'); } const isLt2M = file.size / 1024 / 1024 < 2; if (!isLt2M) { message.error('Image must smaller than 2MB!'); } return isJpgOrPng && isLt2M; } function customRequest(option) { const { onSuccess, one rror, file, onProgress } = option; // 自定义上传处理逻辑,例如使用fetch或者XMLHttpRequest const formData = new FormData(); formData.append('file', file); // 模拟上传 setTimeout(() => { // 模拟成功的响应 onSuccess("success"); // 模拟错误的响应 // one rror("error"); // 模拟上传进度 // onProgress({ percent: 50 }); }, 1000); } const Demo = () => ( <Upload name="file" onRemove={file => { console.log(file); return true; }} beforeUpload={beforeUpload} customRequest={customRequest} > <Button icon={<UploadOutlined />}>Click to Upload</Button> </Upload> ); export default Demo;
自己的例子:
<Form.Item name="csv" label="csv文件" rules={[{ required: true, message: '请上传csv文件!' }]} valuePropName="fileList" getValueFromEvent={normFile} extra="如果上传多个文件,以第一个为准" > <Upload name="content" beforeUpload={beforeUpload} listType="text"> <Button icon={<UploadOutlined />}>点击上传</Button> </Upload> </Form.Item>
去掉了也是OK的
<Upload name="content" action="/upload.do" ....中的action="/upload.do"。标签:const,upload,customRequest,file,import,action,antd,上传 From: https://www.cnblogs.com/zccst/p/18189249