使用Express和Multer,我们可以将文件上传到部署了nodejs的服务器。那么我们如何将文件上传到远程服务器呢?
答案 0 :(得分:1)
随着闷热,它真的很简单。将multer作为中间件传递给路由器。 例如,如果要将文件上载到端点/上载文件
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');
答案 1 :(得分:0)
您可以使用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;