我不确定如何将文件类型保存到我在节点中所在的服务器。这是我的目标:
我需要在后端访问一组对象,并根据某些条件将文件保存在这些对象中,因此我想避免使用表单或只允许文件上传的中间件。
我尝试在网上寻找不同的解决方案,但似乎没有一个适合我所寻找的。
试试这个
const express = require('express');
const fs = require('fs');
const app = express();
const port = 3000;
// Middleware to handle raw data
app.use('/uploadFile', (req, res, next) => {
let data = []; // Array to hold incoming data
req.on('data', chunk => {
data.push(chunk);
});
req.on('end', () => {
req.rawBody = Buffer.concat(data);
next();
});
});
app.post('/uploadFile', async (req, res) => {
const fileData = req.rawBody;
const fileName = req.headers['x-file-name']; // Assume file name is sent in headers
const path = `./uploads/${fileName}`;
try {
// Check if the uploads directory exists, create if not
if (!fs.existsSync('./uploads')) {
fs.mkdirSync('./uploads', { recursive: true });
}
// Write file to the filesystem
fs.writeFileSync(path, fileData);
res.send({ message: "File uploaded successfully" });
} catch (error) {
res.status(500).send({ message: "Failed to upload file", error: error.message });
}
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});