还不会文件上传?React+Node.js前后端上传文件至阿里云OSS全过程
// 前端React组件中的文件上传方法
uploadFile = async (file) => {
const formData = new FormData();
formData.append('file', file);
try {
const response = await axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
console.log('File uploaded successfully:', response.data);
} catch (error) {
console.error('Error uploading file:', error);
}
};
// Node.js后端代码
const express = require('express');
const multer = require('multer');
const aliOssClient = require('ali-oss'); // 需要安装ali-oss包
const upload = multer({ dest: 'uploads/' }); // 配置上传目录
const client = aliOssClient({
region: '<Your-Region>',
accessKeyId: '<Your-Access-Key-Id>',
accessKeySecret: '<Your-Access-Key-Secret>',
bucket: '<Your-Bucket-Name>',
});
const app = express();
app.post('/upload', upload.single('file'), async (req, res) => {
const file = req.file;
const result = await client.put(file.originalname, file.path);
res.status(200).json({ url: result.url });
});
app.listen(3001, () => {
console.log('Server is running on port 3001');
});
这个代码实例展示了如何在React前端使用axios
发送文件到Node.js后端,后端使用multer
处理上传的文件,并使用ali-oss
包将文件上传到阿里云OSS。代码简洁,并包含了错误处理。
评论已关闭