乐闻世界logo
搜索文章和话题

How should customRequest be set in the Ant Design Upload component to work with an XMLHttpRequest?

1个答案

1

When using the Upload component in Ant Design, if you need to customize the upload behavior—for example, by replacing the default upload method with XMLHttpRequest—you can achieve this by setting the customRequest property of the Upload component. This property allows you to override the internal upload logic.

Here is an example of implementing the upload functionality using the customRequest property, where XMLHttpRequest is used for file uploads:

jsx
import React from 'react'; import { Upload, Button } from 'antd'; import { UploadOutlined } from '@ant-design/icons'; const CustomUpload = () => { const customRequest = ({ file, onSuccess, onError, onProgress }) => { const formData = new FormData(); formData.append('file', file); const xhr = new XMLHttpRequest(); // Listen to upload progress events xhr.upload.onprogress = (event) => { if (event.lengthComputable) { const percent = Math.round((event.loaded / event.total) * 100); onProgress({ percent }, file); } }; // Triggered when the request is successfully completed xhr.onload = () => { if (xhr.status === 200) { onSuccess(JSON.parse(xhr.responseText), file); } else { onError(new Error('Upload failed')); } }; // Triggered when the request encounters an error xhr.onerror = () => { onError(new Error('Upload error')); }; // Set the request method, URL, and initiate the request xhr.open('POST', 'Your upload URL', true); xhr.send(formData); }; return ( <Upload customRequest={customRequest}> <Button icon={<UploadOutlined />}>Click to upload</Button> </Upload> ); }; export default CustomUpload;

In this example, we define the customRequest function, which accepts an object parameter containing the file object, success callback onSuccess, error callback onError, and progress callback onProgress. We create a FormData instance, add the file to it, and then send this FormData to the server using XMLHttpRequest.

With this setup, you can fully control the upload process, including handling progress, success, and failure logic. This is particularly useful when you need to customize the upload process—for instance, by adding additional security measures or using different request parameters or headers.

2024年8月9日 20:49 回复

你的答案