Post file from one server to another,using node.js , needle , busboy/multer

前端 未结 3 1666
囚心锁ツ
囚心锁ツ 2021-01-25 23:11

I would like to move a small image from one server to another (both running node). As I search, I haven\'t found enough. This post remains unanswered.

As I started expe

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-25 23:41

    'use strict';
    
    const express   = require('express');
    const multer= require('multer');
    const concat = require('concat-stream');
    const request = require('request');
    
    const router = express.Router();
    
    function HttpRelay (opts) {}
    
    
    HttpRelay.prototype._handleFile = function _handleFile (req, file, cb) {
        file.stream.pipe(concat({ encoding: 'buffer' }, function (data) {
            const r = request.post('/Endpoint you want to upload file', function (err, resp, body) {
    
                if (err) return cb(err);
                req.relayresponse=body;
                cb(null, {});
            });
    
            const form = r.form();
            form.append('uploaded_file', data, {
                filename: file.originalname,
                contentType: file.mimetype
            });
        }))
    };
    
    HttpRelay.prototype._removeFile = function _removeFile (req, file, cb) {
        console.log('hello');
        cb(null);
    };
    
    const relayUpload = multer({ storage: new HttpRelay() }).any();
    
    router.post('/uploadMsgFile', function(req, res) {
        relayUpload(req, res, function(err) {
    
            res.send(req.relayresponse);
    
        });
    });
    
    module.exports = router;
    

    see multer does all the tricks for you. you just have to make sure you use no middle-ware but multer to upload files in your node starting point. Hope it does the tricks for you also.

提交回复
热议问题