import React, { useState } from 'react';
function UploadPDF() {
const [selectedFile, setSelectedFile] = useState(null);
const handleFileChange = (event) => {
const file = event.target.files[0];
if (file && file.type === 'application/pdf') {
setSelectedFile(file);
} else {
alert('请上传PDF文件!');
setSelectedFile(null);
}
};
const handleUpload = async () => {
if (!selectedFile) {
alert('请先选择一个PDF文件!');
return;
}
// 这里你可以将文件上传到服务器
// 例如使用fetch或者axios发送POST请求
// 以下是一个使用fetch的示例
const formData = new FormData();
formData.append('file', selectedFile);
try {
const response = await fetch('你的上传API地址', {
method: 'POST',
body: formData,
});
const result = await response.json();
console.log('上传成功', result);
} catch (error) {
console.error('上传失败', error);
}
};
return (
<div>
<input type="file" onChange={handleFileChange} accept="application/pdf" />
<button onClick={handleUpload}>上传PDF</button>
</div>
);
}
export default UploadPDF;
02-06
2990
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
12-02
1478
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-27
4851
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-19
364
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)