I'm trying to upload multiples files with a modal that contains a form with an input.
My modal (jade template format) :
#modalAddFile.modal
form#uploadForm(enctype='multipart/form-data', action='/#{category}/addFiles', method='post')
.modal-content
.file-field.input-field
.btn
span Ajouter
input(type='file', name='songs', multiple)
.file-path-wrapper
input.file-path.validate(type='text')
.modal-footer
a#cancel.modal-action.modal-close.waves-effect.waves-red.btn-flat(href='#!') Annuler
button#addFile.modal-action.modal-close.waves-effect.waves-green.btn-flat(type='submit', name='action', href='#!') Valider
routes.js :
var express = require('express');
var router = express.Router();
//Upload file
var multer = require('multer');
var upload = multer({ dest: '../public/test/' });
//Add files
router.post('/:category/addFiles', upload.array('songs'), function (req, res, next) {
res.redirect('/');
});
module.exports = router;
I don't have any apparent error (200 success), I don't know what is wrong.
Try to use this code:
var express = require('express');
var router = express.Router();
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '../public/test/')
},
filename: function (req, file, cb) {
cb(null, file.fieldname)
}
});
var upload = multer({ storage: storage });
//Add files
router.post('/:category/addFiles', upload.any(), function (req, res, next) {
res.redirect('/');
});
module.exports = router;
Related
i use multer according to it's readme file in github
it's readme said call multer in middleware like this:
app.js
var multer = require('multer')
app.post('/upload', upload.single('image'), function(req, res){})
but i defined my function(req, res) in another file - post.js - and my code in app.js looks like this:
app.post('/upload', upload.single('image'), post.new)
how can i require multer only on post.js, almost like this:
post.js
var multer = require('multer')
module.exports.new = function(req, res){
//access to req.file
}
app.js
app.post('/upload', post.new)
I can think of two ways.
Firstly, you could expose new as an array:
module.exports.new = [upload.single('image'), function(req, res) {
...
}];
Secondly, you could use multer within your function:
var imageUpload = upload.single('image');
module.exports.new = function(req, res) {
imageUpload(req, res, function(err) {
// Put the rest of your code here
});
};
In this second approach we're just invoking the multer middleware function ourselves, passing it our own function to use as the next callback. There's a little bit more information about doing this at https://github.com/expressjs/multer#error-handling though it describes the technique in a slightly different context.
For MVC structure You can simply do this by :
function Uploader(req, res, next) {
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, your_path);
},
filename: function (req, file, cb) {
cb(null, filename)
}
});
var upload = multer({
storage: storage
});
return upload;
}
module.exports = Uploader
In another file you can simply use
app.post('/upload', Uploader.single('image'), function(req, res){})
If you don't want to create function, you can do the following:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, upload_filePath)
},
filename: function (req, file, cb) {
cb(null,filename)
}
})
var upload= multer({
storage : upload
})
module.exports.upload=upload;
Both gives same result but using Function is more appropriate way.
I'm trying to upload a file into my project using multer, but I have no idea how to do it.
here's some of the code I wrote thinking it could work
// here's my ejs view
<form action="/wistia" method="post" enctype="multipart/form-data">
<input type="file" name="archivo">
<input type="submit">
</form>
// here's my route file
const multer = require("multer");
const express = require('express');
const router = express.Router();
let location = path.join(__dirname, '/uploads');
let upload = multer({ dest: location });
router.get("/wistia",function(req, res){
res.render("wistia");
});
router.post("/wistia", upload.single("archivo") , function(req, res) {
console.log(req.file);
});
thanks.
Try making this change
var upload = multer({
storage: multer.diskStorage({
destination: function (req, file, cb) {
cb(null,location);
}
})
});
var express = require('express');
var router = express.Router(),
multer = require('multer');
var uploading = multer({
dest: __dirname + '../public/uploads/',
})
router.post('/upload', uploading, function(req, res) {
console.log('uploaded');
})
I got an error Route.post() requires callback functions error following a photo upload tutorial here. Maybe it's cause by the newer version of expresss? I remember above is the way how we put middle in a route, but why here it doesn't work?
Basing on the multer docs, it seems like you have to use uploading.single() or uploading.array() as your middleware. This example is obtained from the example usage in the multer docs:
var upload = multer({ dest: 'uploads/' })
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
var express = require('express');
var router = express.Router(),
multer = require('multer');
var uploading = multer({
dest: __dirname + '../public/uploads/',
})
var type = uploading.single('file');
router.post('/upload', type, function(req, res) {
console.log('uploaded');
})
I'm using angular file upload which previously did work when I used Laravel Lumen for the backend but I've moved to Node and unable to return the file contents of an upload.
FRONT END ANGULAR
$scope.upload = Upload.upload({
url: ENV.apiEndpoint + '/upload',
method: 'POST',
data: {
fname: $scope.fname
},
file: file
}).progress(function(evt) {
}).success(function(data, status, headers, config) {
});
BACK END NODE
upload/index.js
'use strict';
var express = require('express');
var controller = require('./upload.controller');
var router = express.Router();
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './my-uploads');
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now());
}
})
var upload = multer({ storage: storage });
router.post('/', upload.single('file'), controller.index);
module.exports = router;
upload/upload.controller.js
'use strict';
var _ = require('lodash');
var db = require('../../db');
var https = require('https');
var Q = require('q');
var fs = require('fs');
var multer = require('multer');
exports.index = function(req, res, next) {
console.log(req.files.file);
res.status(204).end();
};
Old Laravel Lumen Request
public function data(Request $request) {
$path_parts = pathinfo($_FILES["file"]["name"]);
$extension = $path_parts['extension'];
$contents = file_get_contents( $_FILES['file']['tmp_name'] );
return response()->json(['type'=> $extension, 'content'=> $contents]);
}
All I'm looking to do is upload a file but only return the contents of the file to the front end again I dont want the file to be stored.
Here you have an example, you have a couple of things wrong. Check it out
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/images/banks')
},
filename: function (req, file, cb) {
crypto.pseudoRandomBytes(16, function (err, raw) {
cb(null, raw.toString('hex') + path.extname(file.originalname));
});
}
});
var upload = multer({storage: storage});
router.post('/uploadImage', upload.single('file'), function (req, res, next) {
if(!req.file) {
res.status(400);
res.send({error: 'No se pudo subir el archivo'});
}
res.send({filename: req.file.filename});
});
I am a fresher on Javascript and Node JS. I am looking for the solution to upload a zip file which contains pictures only and give these pictures permanent link. For now I can upload a zip file and extract all pictures in it as below:
var express = require('express');
var router = express.Router();
var multer = require('multer');
var fs = require('fs');
var AdmZip = require('adm-zip');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads/');
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
var upload = multer({ storage: storage }).any();
/* get home page. */
router.get('/', function (req, res) {
res.render('index', { title: 'express' });
});
router.post('/', upload, function (req, res) {
var zip = new AdmZip("./public/uploads/Camera Roll.zip");
zip.extractAllTo('public/uploads/', true);
res.send(req.files);
});
module.exports = router;
Once I upload a zip file I saved it in 'public/uploads/'. How can I get the path which save uploaded zip file because now I just identify it in my code (var zip = new AdmZip("./public/uploads/Camera Roll.zip");). Is there any variable to denote it? And once I unzip the file all pictures are in the folder 'public/uploads', does that mean I gave a permanent link to all pictures?
I've found. Just use req.file.path but need to use var upload = multer({ storage: storage }).single(filename) firstly;