Rakesh Saini
Rakesh Saini

Reputation: 763

How To Send Files From One Nodejs Server To Another Nodejs Server using POST request and save into folder?

I want to send some image file from one Nodejs server to another Nodejs server. And how to get the file in second server? Also how to save into a folder in second server? How to do that any suggestion?

First server

    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);
    })
}

Second server

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

    }
);

When console.log i am getting following result in Second server file enter image description here

But Image is not saved in the asset folder. Multer and storage are fine. When i uploaded Image to Second server directly its working fine.

Upvotes: 0

Views: 2243

Answers (1)

Amr shadid
Amr shadid

Reputation: 31

The first thing you need to do is create an API using node/Express.js and create store using 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));
    }
});

Build the image filter function:

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;

Create an API to handle image get from request:

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`);
    });
});  

Now you have the server side accept the image from request and save it on file. After that, let us go back to the other server. On other server it's like a client and we need create request to the API upload-pic . To do that you can use axios package and form-data package.

Handling File Uploads

Upvotes: 1

Related Questions