forked from trulymittal/nodejs-file-upload
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
71 lines (59 loc) · 1.75 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
const express = require('express')
const fileUpload = require('express-fileupload')
const path = require('path')
const app = express()
app.set('view engine', 'ejs')
app.use(
fileUpload({
useTempFiles: true,
tempFileDir: path.join(__dirname, 'tmp'),
createParentPath: true,
limits: { fileSize: 2 * 1024 * 1024 },
})
)
app.get('/', async (req, res, next) => {
res.render('index')
})
app.post('/single', async (req, res, next) => {
try {
const file = req.files.mFile
console.log(file)
const fileName = new Date().getTime().toString() + path.extname(file.name)
const savePath = path.join(__dirname, 'public', 'uploads', fileName)
if (file.truncated) {
throw new Error('File size is too big...')
}
if (file.mimetype !== 'image/jpeg') {
throw new Error('Only jpegs are supported')
}
await file.mv(savePath)
res.redirect('/')
} catch (error) {
console.log(error)
res.send('Error uploading file')
}
})
app.post('/multiple', async (req, res, next) => {
try {
const files = req.files.mFiles
// files.forEach(file => {
// const savePath = path.join(__dirname, 'public', 'uploads', file.name)
// await file.mv(savePath)
// })
// let promises = []
// files.forEach((file) => {
// const savePath = path.join(__dirname, 'public', 'uploads', file.name)
// promises.push(file.mv(savePath))
// })
const promises = files.map((file) => {
const savePath = path.join(__dirname, 'public', 'uploads', file.name)
return file.mv(savePath)
})
await Promise.all(promises)
res.redirect('/')
} catch (error) {
console.log(error)
res.send('Error uploading files...')
}
})
app.listen(3000, () => console.log('🚀 server on port 3000'))