1

With Express and Multer, we can upload file to the server where nodejs is deployed. Then how can we upload files to a remote server?

Ng2-Fun
  • 3,307
  • 9
  • 27
  • 47

2 Answers2

1

With multer, its really simple. Pass multer as a middleware to your router. For example, if you want to upload your file to your endpoint /uploadfile

app.post('/uploadfile', multer_middleware, function(req, res){
    res.end("uploaded");
});

multer_middleware would be like this.

var multer_middleare = multer({ dest: './path_to_storage',
    onFileUploadComplete: function (file) {
        // after file is uploaded, upload it to remote server
        var filename = file.name;

        request({
            method: 'PUT',
            preambleCRLF: true,
            postambleCRLF: true,
            uri: 'http://remote-server.com/upload',
            auth: {
                'user': 'username',
                'pass': 'password',
                'sendImmediately': false
            },
            multipart: [
                { body: fs.createReadStream('./path_to_storage/' + filename) }
            ]
        },
        function (error, response, body) {
            if (error) {
                return console.error('upload failed:', error);
            }
            console.log('Upload successful!  Server responded with:', body);
        })
    });

After the file is uploaded, you can use HTTP client like request to upload it to remote server.

Don't forget to import multer at the beginning of your file

var multer  = require('multer');
  • Sorry, can you explain more details. In this way, can it only upload files to the server where node.js runs? I run node.js in my laptop, and I want to upload file to a remote server, can multer do that? If so, where and how can I put the url, username and password to connect to remote server? – Ng2-Fun Mar 11 '16 at 04:48
-1

You can use heroku to deploy it, and use Cloudinary to upload them to the cloud.

//requiring cloudinary and multer

const cloudinary = require('cloudinary');
const cloudinaryStorage = require('multer-storage-cloudinary');
const multer = require('multer');

cloudinary.config({
  cloud_name: process.env.CLOUDINARY_NAME,
  api_key: process.env.CLOUDINARY_KEY,
  api_secret: process.env.CLOUDINARY_SECRET
});

var storage = cloudinaryStorage({
  cloudinary,
  folder: 'assets', // The name of the folder in cloudinary
  allowedFormats: ['jpg', 'png', 'jpeg', 'gid', 'pdf'],
  filename: function (req, file, cb) {
    cb(null, file.originalname); // The file on cloudinary would have the same name as the original file name
  }
});


const uploadCloud = multer ({ storage: storage})
//const uploadCloud = multer({ storage: storage }).single('file');

module.exports = uploadCloud;