Compare commits
3 Commits
f31e079373
...
5473d82b21
| Author | SHA1 | Date | |
|---|---|---|---|
| 5473d82b21 | |||
| 222d55e360 | |||
| 4b6f8b4bec |
11
app.js
11
app.js
@@ -25,17 +25,8 @@ app.use(sassMiddleware({
|
|||||||
app.use(express.static(path.join(__dirname, 'public')));
|
app.use(express.static(path.join(__dirname, 'public')));
|
||||||
|
|
||||||
app.use('/', indexRouter);
|
app.use('/', indexRouter);
|
||||||
|
app.use('/upload', require("./routes/upload"));
|
||||||
|
|
||||||
const multer = require('multer');
|
|
||||||
var upload = multer({ dest: 'uploads/' })
|
|
||||||
app.post('/upload', upload.single('photo'), (req, res) => {
|
|
||||||
console.log(req.headers);
|
|
||||||
if (req.file) {
|
|
||||||
res.sendStatus(200);
|
|
||||||
} else {
|
|
||||||
res.sendStatus(400);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
// catch 404 and forward to error handler
|
// catch 404 and forward to error handler
|
||||||
app.use(function(req, res, next) {
|
app.use(function(req, res, next) {
|
||||||
next(createError(404));
|
next(createError(404));
|
||||||
|
|||||||
33
routes/upload.js
Normal file
33
routes/upload.js
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
const express = require('express');
|
||||||
|
const router = express.Router();
|
||||||
|
const multer = require('multer');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
// rotating filename
|
||||||
|
const nMaxPhotos = 100;
|
||||||
|
var photoCounter = 0;
|
||||||
|
const storage = multer.diskStorage({
|
||||||
|
destination: function (req, file, cb) {
|
||||||
|
cb(null, './uploads');
|
||||||
|
},
|
||||||
|
filename: function (req, file, cb) {
|
||||||
|
filename = path.parse(file.originalname).name + "-" +
|
||||||
|
(photoCounter % nMaxPhotos).toString().padStart(2, '0') + ".jpg";
|
||||||
|
cb(null, filename);
|
||||||
|
photoCounter += 1;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const upload = multer({ storage: storage });
|
||||||
|
|
||||||
|
router.post('/', upload.single('photo'), (req, res) => {
|
||||||
|
if (req.file) {
|
||||||
|
console.log("Received photo, saved as:", req.file.path, ", size:",
|
||||||
|
req.file.size);
|
||||||
|
res.sendStatus(200);
|
||||||
|
} else {
|
||||||
|
res.sendStatus(400);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
module.exports = router;
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
extends layout
|
doctype html
|
||||||
|
html(lang='en')
|
||||||
block content
|
head
|
||||||
h1= title
|
title Simple multipart/form-data example
|
||||||
p Welcome to #{title}
|
body
|
||||||
form(action='/upload' enctype='multipart/form-data' method='POST')
|
form(action='/upload' enctype='multipart/form-data' method='POST')
|
||||||
input(type='file' name='photo')
|
input(type='file' name='photo')
|
||||||
input(type='submit' value='Upload a file')
|
input(type='submit' value='Upload a file')
|
||||||
|
|||||||
Reference in New Issue
Block a user