Browse Source

multer naming options and sanitization

master
Rich Brown 1 year ago
parent
commit
64855eea87
1 changed files with 19 additions and 25 deletions
  1. +19
    -25
      routes/createRouter.js

+ 19
- 25
routes/createRouter.js View File

@@ -3,44 +3,38 @@ import multer from 'multer';
// import Micropub from 'micropub-helper';
import fs from 'fs';

// const storage = multer.memoryStorage();
const upload = multer({ dest: 'uploads/' });
const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, 'uploads/');
},
filename(req, file, cb) {
cb(null, `${file.originalname}-${Date.now()}`);
},
});
const upload = multer({ storage });

const createRouter = express.Router();

/* TODO: sanitize

function sanitizeFile(file, cb) {
// Define the allowed extension
let fileExts = ['png', 'jpg', 'jpeg', 'gif']
// Check allowed extensions
let isAllowedExt = fileExts.includes(file.originalname.split('.')[1].toLowerCase());
// Mime type must be an image
let isAllowedMimeType = file.mimetype.startsWith("image/")
if(isAllowedExt && isAllowedMimeType){
return cb(null ,true) // no errors
}
else{
// pass error msg to callback, which can be displaye in frontend
cb('Error: File type not allowed!')
}
}
*/
const sanitizeFile = (file) => {
const fileExts = ['png', 'jpg', 'jpeg', 'gif'];
const isAllowedExt = fileExts.includes(file.originalname.split('.')[1].toLowerCase());
const isAllowedMimeType = file.mimetype.startsWith('image/');
return (isAllowedExt && isAllowedMimeType);
};

createRouter.post('/form', upload.single('file'), (req, res) => {
const { file, body: { title, body, arrayOfTags } } = req;
if (!sanitizeFile()) {
res.status(403).json({ error: 'not an allowed filetype', url: null });
}
return req.app.locals.mp
.create(
{
h: 'entry',
name: title, // i thought MF syntax was 'p-name' but voxpelli's formattr turns NAME to TITLE
name: title,
content: body,
category: arrayOfTags,
photo: fs.createReadStream(file.path),
// photo: JSON.stringify({
// filename: file.originalname,
// buffer: file.buffer,
// }),
},
'multipart',
)


Loading…
Cancel
Save