Skip to content

Instantly share code, notes, and snippets.

@ahrherrera
Last active February 5, 2019 20:27
Show Gist options
  • Save ahrherrera/dc0448e9bc17dfbbc445ab41f32a478c to your computer and use it in GitHub Desktop.
Save ahrherrera/dc0448e9bc17dfbbc445ab41f32a478c to your computer and use it in GitHub Desktop.
Multer file upload
var express = require("express");
var router = express.Router();
var accountModel = require("../models/account/account"); // gf
const multer = require('multer');
// FileUpload Setup
const storage = multer.diskStorage({
destination: function(req, file, cb) {
//Directorio donde guardar imagen
cb(null, 'public/images');
},
filename: function(req, file, cb) {
//Combina caracteres aleatorios y el nombre de archivo
cb(null, Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15) + file.originalname);
}
});
const fileFilter = (req, file, cb) => {
// acceptFile
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
//rejectFile
cb(null, false);
}
};
const upload = multer({
storage: storage,
limits: {
//Coloca el max file size
fileSize: 1024 * 1024 * 5
},
fileFilter: fileFilter
});
//Para enviar el archivo, tienes que utilizar el FileKey que insertas como parametro en upload.single
router.get("/updateUser", upload.single('picUrl'), function(req, res, next) {
accountModel // call the promise
.updateUser(req)
.then(
//req.file contiene toda la info del archivo, incluyendo el nombre.
function(response) { //success
console.log("Success!");
res.send(response); //return the data
},
function(error) { //failed
console.error("Failed!", error);
res.status(404).send(error); //return error with 404
}
)
.catch(function(ex) { //exception
console.error("Exception!", ex);
res.status(500).send(ex); //return exception with 500
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment