node(multer)上传文件
from表单上传文件
前端代码
html
import React from 'react';
import { Form, Button, Upload, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import axios from 'axios';
const FileUploadForm = () => {
const onFinish = async (values) => {
const formData = new FormData();
const file = values.file[0].originFileObj; // 获取文件
formData.append('file', file);
try {
const response = await axios.post('http://localhost:5000/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
message.success('文件上传成功');
} catch (error) {
message.error('文件上传失败');
}
};
return (
<Form onFinish={onFinish}>
<Form.Item
name="file"
label="上传文件"
rules={[{ required: true, message: '请选择一个文件!' }]}
>
<Upload
beforeUpload={() => false} // 阻止自动上传,手动处理上传
accept=".jpg,.png,.pdf,.docx,.txt" // 设置文件类型限制
>
<Button icon={<UploadOutlined />}>选择文件</Button>
</Upload>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
上传
</Button>
</Form.Item>
</Form>
);
};
export default FileUploadForm;
后端代码
javascript
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const PORT = 5000;
// 配置 multer 存储选项
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads/'); // 文件保存的目录
},
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname)); // 保证文件名唯一
},
});
// 创建 multer 实例
const upload = multer({ storage: storage });
// 创建上传路由
app.post('/upload', upload.single('file'), (req, res) => {
// 检查文件是否上传
if (!req.file) {
return res.status(400).send('没有文件上传');
}
res.status(200).send({
message: '文件上传成功',
file: req.file,
});
});
// 设置静态目录,使得可以通过 URL 访问上传的文件
app.use('/uploads', express.static('uploads'));
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});