【问题标题】:nodejs upload files to a remote server with Multer?nodejs 使用 Multer 将文件上传到远程服务器?
【发布时间】:2018-07-13 05:59:32
【问题描述】:

使用 Express 和 Multer,我们可以将文件上传到部署 nodejs 的服务器。那么我们如何将文件上传到远程服务器呢?

【问题讨论】:

标签: node.js multer


【解决方案1】:

有了 multer,它真的很简单。将 multer 作为中间件传递给您的路由器。 例如,如果您想将文件上传到端点 /uploadfile

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

multer_middleware 应该是这样的。

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

文件上传后,您可以使用request等HTTP客户端将其上传到远程服务器。

不要忘记在文件开头导入 multer

var multer  = require('multer');

【讨论】:

  • 对不起,你能解释更多细节吗?这样一来,是不是只能把文件上传到node.js运行的服务器上呢?我在笔记本电脑上运行 node.js,我想将文件上传到远程服务器,multer 可以这样做吗?如果是这样,我可以在哪里以及如何放置 url、用户名和密码以连接到远程服务器?
【解决方案2】:

您可以使用 heroku 来部署它,并使用 Cloudinary 将它们上传到云端。

//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;

【讨论】:

    猜你喜欢
    • 2015-03-09
    • 1970-01-01
    • 2015-12-13
    • 2018-04-23
    • 1970-01-01
    • 2021-05-03
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多