This repository has been archived by the owner on Jun 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
159 lines (136 loc) · 4.48 KB
/
index.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
//
// MongoDB GridFS example project
//
// Require dependencies
const express = require('express');
const mongo = require('mongodb');
const Busboy = require('busboy');
const uuid4 = require('uuid').v4;
const bodyParser = require('body-parser');
// Create app
const app = express();
const port = 80;
// Set up middlewares
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
// MongoDB URI
const uri = 'mongodb://localhost';
// Connect to MongoDB
mongo.MongoClient.connect(uri, { useUnifiedTopology: true }, (err, client) => {
if (err) throw err;
// Use 'mongofiles' database within MongoDB
const db = client.db('mongofiles');
// Set 'cloud' collection as GridFS storage
const GridFS = new mongo.GridFSBucket(db, { bucketName: 'cloud' });
/**
* @rotue GET /
* @desc Load all files and render index page
*/
app.get('/', (req, res) => {
GridFS.find().toArray((error, files) => {
if (!files || !files.length) {
res.render('index', { files: null });
} else {
files.map(file => {
if (file.hasOwnProperty('contentType')) {
file.isImage = ['image/jpeg', 'image/png'].includes(file.contentType);
}
});
res.render('index', { files });
}
});
});
/**
* @route POST /upload
* @desc Upload a file to GridFS
*/
app.post('/upload', (req, res) => {
// Create Busboy instance
const busboy = new Busboy({ headers: req.headers });
// Listen for files in the request stream
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
let writable;
// When receiving data open upload stream and start sending data
file.on('data', data => {
if (!writable) writable = GridFS.openUploadStreamWithId(uuid4(), filename, { contentType: mimetype });
writable.write(data, null, err => console.log('write', err));
});
// Stop sending data when no more data is received
file.on('end', () => {
if (writable) writable.end(null, null, (err, result) => console.log('end', err, result));
});
});
// Listen for any other non-file fields
busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => {
req.body[fieldname] = val;
});
// Run when busboy read all the data from the request stream
busboy.on('finish', () => {
console.log('request body:', req.body);
res.redirect('/');
});
// Pipe request stream into busboy
req.pipe(busboy);
});
/**
* @route GET /files
* @desc Display all files as json
*/
app.get('/files', (req, res) => {
db.collection('cloud.files').find({}, {}, (error, files) => {
if (error) return res.status(500).json({ error });
files.toArray((err, files) => {
if (!files || !files.length) {
return res.status(404).json({ error: 'No files exist.' });
} else {
return res.json(files);
}
});
});
});
/**
* @route GET /files/:id
* @desc Display file as json object
*/
app.get('/files/:id', (req, res) => {
db.collection('cloud.files').findOne({ _id: req.params.id }, {}, (error, file) => {
if (!file) {
res.status(404).json({ error: 'File not found.' });
} else {
res.json(file);
}
});
});
/**
* @route GET /image/:id
* @desc Download an image
*/
app.get('/image/:id', (req, res) => {
db.collection('cloud.files').findOne({ _id: req.params.id }, {}, (error, file) => {
if (!file) {
res.status(404).json({ error: 'File not found.' });
} else if (!['image/jpeg', 'image/png'].includes(file.contentType)) {
res.status(400).json({ error: 'File is not an image.' });
} else {
const readable = GridFS.openDownloadStream(file._id);
readable.pipe(res);
}
});
});
/**
* @route POST /delete/:id
* @desc Delete a file
*/
app.post('/delete/:id', (req, res) => {
GridFS.delete(req.params.id, error => {
if (error) {
res.status(500).json({ error });
} else {
res.redirect('/');
}
});
});
});
// Start listening
app.listen(port, () => console.log(`Server listening on port ${port}.`));