【发布时间】:2018-07-13 05:59:32
【问题描述】:
使用 Express 和 Multer,我们可以将文件上传到部署 nodejs 的服务器。那么我们如何将文件上传到远程服务器呢?
【问题讨论】:
-
关注此网址。它可能会帮助你stackoverflow.com/a/32139236/8686459
使用 Express 和 Multer,我们可以将文件上传到部署 nodejs 的服务器。那么我们如何将文件上传到远程服务器呢?
【问题讨论】:
有了 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');
【讨论】:
您可以使用 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;
【讨论】: