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

前端 未结 3 1646
囚心锁ツ
囚心锁ツ 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条回答
  •  Happy的楠姐
    2021-01-25 23:53

    I solved my problem by using the following code,

    server1 (using needle) :

    app.post("/move_img", function(req, res) {
        console.log("post handled")
    
        var data = {
            image:{
            file: __dirname + "/img_to_move.jpg",
            content_type: "image/jpeg"}
        }
    
        needle.post(server2 + "/post_img", data, {
            multipart: true
        }, function(err,result) {
            console.log("result", result.body);
        });
    })
    

    Server 2:

    app.use('/post_img',multer({
        dest: '.uploads/images',
        rename: function(fieldname, filename) {
            return filename;
        },
        onFileUploadStart: function(file) {
            console.log(file.originalname + ' is starting ...')
        },
        onFileUploadComplete: function(file) {
            console.log(file.fieldname + ' uploaded to  ' + file.path)
        }
    }));
    
    app.post('/post_img', function(req, res) {
    
        console.log(req.files);
        res.send("File uploaded.");
    
    });
    

    An alternative for the server 1 is the following (using form-data module):

    var form = new FormData();
    form.append('name', 'imgTest.jpg');
    form.append('my_file', fs.createReadStream(__dirname + "/img_to_move.jpg"));
    
    form.submit(frontend + "/post_img", function(err, result) {
        // res – response object (http.IncomingMessage)  //
        console.log(result);
    });
    

提交回复
热议问题