You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过POST请求在两个Node.js服务器间传输文件并保存至指定目录?及代码问题排查

Let's figure out why your image isn't saving to the asset folder — the core issue lies in how your first Node.js server is sending the file to the second one. Here's a step-by-step fix and explanation:

Problem Analysis

Your first server is converting the file-containing object to a JSON string and sending it with a content-type: application/json header. But Multer is designed to parse multipart/form-data requests (the standard format for file uploads), not JSON. That's why your second server sees data in req.body but can't properly process or save the actual image file.

Solution

Step 1: Fix the File-Sending Logic on the First Server

You need to send a proper multipart/form-data request using FormData, not JSON. Let's rewrite your uploadImage function:

const request = require('request');
const FormData = require('form-data');
const fs = require('fs');

uploadImage(req, callback) {
  const formData = new FormData();
  // Use the temporary file path from req.file (assuming your first server uses Multer too)
  formData.append('file', fs.createReadStream(req.file.path), {
    filename: req.file.originalname,
    contentType: req.file.mimetype
  });

  const options = {
    method: 'POST',
    url: config.db_layer_endpointUpload,
    headers: {
      'api_key': config.db_layer_access_key,
      // Let FormData auto-generate the correct Content-Type header (with boundary)
      ...formData.getHeaders()
    },
    body: formData
  };

  request(options, function (error, response) {
    if (error) {
      return callback(error);
    }
    return callback(response.body);
  });
}

Key changes here:

  • We're reading the temporary file from your first server's filesystem (via req.file.path) and streaming it into the FormData object.
  • We let FormData handle the Content-Type header automatically (this includes the critical boundary string that Multer needs to parse the request).
  • Removed the JSON.stringify call — we're sending the raw FormData as the request body.

Step 2: Confirm the Second Server's Multer Configuration

You mentioned direct uploads work, but let's explicitly ensure Multer is set to save files to your asset folder. Here's a complete configuration example:

const multer = require('multer');
const path = require('path');

// Configure Multer to save files to the asset folder
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './asset'); // Path to your target folder
  },
  filename: function (req, file, cb) {
    // Keep the original filename, or customize it (e.g., add a timestamp)
    cb(null, file.originalname);
  }
});

const multerObj = multer({ storage: storage });

// Updated upload endpoint
app.post("/upload", multerObj.single("file"), (req, res) => {
  // Multer has already saved the file to ./asset at this point
  console.log('File saved successfully:', req.file.path);
  console.log('Request body data:', req.body);
  res.status(200).json({ 
    message: 'File uploaded and saved',
    fileDetails: req.file
  });
});

Why This Works

By sending a proper multipart/form-data request from the first server, you're matching the exact format Multer expects (the same format used when uploading directly to the second server). Multer will automatically parse the request, save the file to your asset folder, and populate req.file with all the file's metadata.

内容的提问来源于stack exchange,提问作者Rakesh Saini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 01:07:44