ant.design 上传组件上传pdf文件后支持打开pdf预览详细代码示例
时间: 2023-11-25 09:07:46 浏览: 488
预览pdf的详细代码
4星 · 用户满意度95%
Ant Design的上传组件支持上传PDF文件并且预览PDF文件需要将PDF文件转换为图片格式,然后使用图片预览组件进行预览。以下是示例代码:
```jsx
import React, { useState } from 'react';
import { Upload, Button, message, Spin } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { pdfjs, Document, Page } from 'react-pdf';
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
const UploadPDF = () => {
const [fileList, setFileList] = useState([]);
const [previewUrl, setPreviewUrl] = useState('');
const [loading, setLoading] = useState(false);
const handleChange = ({ fileList }) => {
setFileList(fileList);
if (fileList.length > 0) {
setLoading(true);
const reader = new FileReader();
reader.readAsDataURL(fileList[0].originFileObj);
reader.onloadend = () => {
setPreviewUrl(reader.result);
setLoading(false);
};
} else {
setPreviewUrl('');
}
};
const handlePreview = () => {
window.open(previewUrl);
};
const handleRemove = () => {
setFileList([]);
setPreviewUrl('');
};
const uploadButton = (
<div>
{loading ? <LoadingOutlined /> : <PlusOutlined />}
<div style={{ marginTop: 8 }}>Upload</div>
</div>
);
return (
<div>
<Upload
fileList={fileList}
onChange={handleChange}
onRemove={handleRemove}
beforeUpload={(file) => {
if (file.type !== 'application/pdf') {
message.error(`${file.name} is not a PDF file`);
return false;
}
return true;
}}
showUploadList={false}
>
{fileList.length === 0 ? (
uploadButton
) : (
<Button onClick={handlePreview}>Preview</Button>
)}
</Upload>
{previewUrl && (
<div style={{ marginTop: 16 }}>
<Spin spinning={loading}>
<Document file={previewUrl} onLoadSuccess={null}>
<Page pageNumber={1} width={400} />
</Document>
</Spin>
</div>
)}
</div>
);
};
export default UploadPDF;
```
在这个示例中,我们使用了`react-pdf`库来渲染PDF文件的预览图。`handleChange`函数在上传PDF文件后将PDF文件转换为DataURL,然后设置预览图的URL。`handlePreview`函数用于打开预览图。`handleRemove`函数用于删除上传的PDF文件和预览图。在上传组件中,`beforeUpload`函数用于验证上传的文件是否为PDF文件。最后,`Document`和`Page`组件用于渲染PDF文件的预览图。
阅读全文