【问题标题】:How To Send Files From One Nodejs Server To Another Nodejs Server using POST request and save into folder?如何使用 POST 请求将文件从一个 Nodejs 服务器发送到另一个 Nodejs 服务器并保存到文件夹中?
【发布时间】:2021-12-22 01:29:03
【问题描述】:

我想将一些图像文件从一个 Nodejs 服务器发送到另一个 Nodejs 服务器。以及如何在第二台服务器中获取文件?另外如何保存到第二台服务器的文件夹中? 有什么建议怎么做?

第一台服务器

    uploadImage(req, callback) {
    var formData = new FormData();
    
    var body = {
        "file": req.file,
    }

    var options = {
        'method': 'POST',
        'url': config.db_layer_endpointUpload,
        'headers': {
            'api_key': config.db_layer_access_key,
            
            'content-type':  'application/json'
        },
        body: JSON.stringify(body),
       
    }
    request(options, function (error, response) {
        return callback(response.body);
    })
}

第二台服务器

    app.post(
    "/upload",
    multerObj.single("file"),
    (req, res) => {
        console.log(req.body);

    }
);

当 console.log 我在第二个服务器文件中得到以下结果

但图像未保存在资产文件夹中。 Multer和存储都很好。当我将图像直接上传到第二台服务器时,它工作正常。

【问题讨论】:

    标签: node.js express post multer


    【解决方案1】:

    您需要做的第一件事是使用 node/Express.js 创建 API 并使用 multer 创建存储:

    const storage = multer.diskStorage({
        destination: function(req, file, cb) {
            cb(null, 'uploads/');
        },
    
        // By default, multer removes file extensions so let's add them back
        filename: function(req, file, cb) {
            cb(null, file.fieldname + '-' + Date.now() + 
            path.extname(file.originalname));
        }
    });
    

    构建图片过滤功能:

    const imageFilter = function(req, file, cb) {
        // Accept images only
        if (!file.originalname.match(/\.(jpg|JPG|jpeg|JPEG|png|PNG|gif|GIF)$/)) {
            req.fileValidationError = 'Only image files are allowed!';
            return cb(new Error('Only image files are allowed!'), false);
        }
        cb(null, true);
    };
    exports.imageFilter = imageFilter;
    

    创建一个 API 来处理从请求中获取图像:

    app.post('/upload-pic', (req, res) => {
        let upload = multer({ storage: storage, fileFilter: helpers.imageFilter }).single('pic');
    
    
        upload(req, res, function(err) {
            // req.file contains information of uploaded file
            // req.body contains information of text fields, if there were any
    
            if (req.fileValidationError) {
                return res.send(req.fileValidationError);
            }
            else if (!req.file) {
                return res.send('Please select an image to upload');
            }
            else if (err instanceof multer.MulterError) {
                return res.send(err);
            }
            else if (err) {
                return res.send(err);
            }
    
            // Display uploaded image for user validation
            res.send(`You have uploaded this image`);
        });
    });  
    

    现在您让服务器端接受来自请求的图像并将其保存在文件中。之后,让我们回到另一台服务器。在其他服务器上,它就像一个客户端,我们需要创建对 API upload-pic 的请求。为此,您可以使用 axios 包和 form-data 包。

    Handling File Uploads

    【讨论】:

    • 感谢您的回复。你的建议工作正常。现在如何将此文件接收到另一个 nodejs 服务器?
    • 如果我理解正确,当请求发生在 '/upload-pic' API 上时,您可以使用相同的请求正文将 Http Post 发送到另一个服务器 Node.js。另一方面,您需要制作相同的 API 来接受请求并处理它。怎么做 ?您可以在验证请求正文时在 '/upload-pic' 中使用 Axios,然后发出 Axios 请求。
    • 我在没有 Axios 的情况下使用,一切都很好,但图像没有上传到文件夹中。
    • 第一件事是确定请求包含图像和API端从请求正文读取图像?
    • 如果你没有使用 Multer 包,试试吧
    猜你喜欢
    • 2018-02-10
    • 2018-04-25
    • 1970-01-01
    • 2022-11-23
    • 2015-07-10
    • 2018-01-12
    • 1970-01-01
    • 2017-09-07
    相关资源
    最近更新 更多