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

I would like to move a small image from one server to another (both are executed by node). When I search, I have not found enough. This post remains unanswered.

When I started experimenting, I wrote the following to the first server:

app.post("/move_img", function(req, res) { console.log("post handled"); fs.readFile(__dirname + "/img_to_move.jpg", function(err, data) { if (err) throw err; console.log(data); needle.post(server2 + "/post_img", { data: data, name : "test.jpg" }, function(result) { console.log(result); res.send("ok"); }); }); }); 

This part seems to work, since I can write data on the same server (using fs.writeFile), recreate img.

Now when I try to process the message on another server, I have a problem.

Server2:

 app.post('/post_img', [ multer({ dest: './uploads/images'}), function(req, res) { console.log("body ",req.body) // form fields console.log("files ",req.files) // form files res.send("got it"); }]); 

Thus, I get an empty object in the files and in the body: { 'headers[Content-Type]': 'application/x-www-form-urlencoded', 'headers[Content-Length]': '45009' }

I think I could use busboy as an alternative, but I can't get it to work. Any advice, tutorials would be welcome.

0
multer busboy
source share
2 answers

I solved my problem using the following code,

server1 (using the 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 server 1 is the following (using the 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); }); 
0
source share

I would just read your file from the first server using the readFile () function, and then write it to another server using the function writeFile () .

Here you can see the use of both functions on one of my servers.

0
source share

All Articles