使用 Node js Express 将文件保存到服务器

问题描述 投票:0回答:1

我不确定如何将文件类型保存到我在节点中所在的服务器。这是我的目标:

我需要在后端访问一组对象,并根据某些条件将文件保存在这些对象中,因此我想避免使用表单或只允许文件上传的中间件。

VS Ex

我尝试在网上寻找不同的解决方案,但似乎没有一个适合我所寻找的。

node.js express file-upload
1个回答
0
投票

试试这个

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}`);
});
© www.soinside.com 2019 - 2024. All rights reserved.