Skip to content

Instantly share code, notes, and snippets.

@qkreltms
Last active September 12, 2018 06:50
Show Gist options
  • Select an option

  • Save qkreltms/1919d0b0a83d0a7680ea30d8831a0f17 to your computer and use it in GitHub Desktop.

Select an option

Save qkreltms/1919d0b0a83d0a7680ea30d8831a0f17 to your computer and use it in GitHub Desktop.
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const crypto = require('crypto');
const mongoose = require('mongoose');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const app = express();
// Middleware
app.use(bodyParser.json());
app.set('view engine', 'ejs');
// Mongo URI
const mongoURI = 'mongodb://localhost/imgSaveTest';
// Create mongo connection
const conn = mongoose.createConnection(mongoURI);
// Init gfs
let gfs;
conn.once('open', () => {
// Init stream
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('uploads');
});
// Create storage engine
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
//랜덤생성된 이름 + 확장자
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'uploads'
};
resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });
// @route GET /
// @desc Loads form
app.get('/', (req, res) => {
res.render('index');
});
// @route POST /upload
// @desc Uploads a file to DB
app.post('/upload', upload.single('file'), (req, res) => {
res.json({ file: req.file });
//res.redirect('/');
});
// @route GET /files
// @desc Display all files in JSON
app.get('/files', (req, res) => {
gfs.files.find().toArray((err, files) => {
// Check if files
if (!files || files.length === 0) {
return res.status(404).json({
err: 'No files exist'
});
}
// Files exist
return res.json(files);
});
});
// @route GET /files/:filename
// @desc Display single file object
app.get('/files/:filename', (req, res) => {
gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
// Check if file
if (!file || file.length === 0) {
return res.status(404).json({
err: 'No file exists'
});
}
// File exists
return res.json(file);
});
});
// @route GET /image/:filename
// @desc Display Image
app.get('/image/:filename', (req, res) => {
gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
// Check if file
if (!file || file.length === 0) {
return res.status(404).json({
err: 'No file exists'
});
}
// Check if image
if (file.contentType === 'image/jpeg' || file.contentType === 'image/png') {
// Read output to browser
const readstream = gfs.createReadStream(file.filename);
readstream.pipe(res);
} else {
res.status(404).json({
err: 'Not an image'
});
}
});
});
// @route DELETE /files/:id
// @desc Delete a file
app.delete('/files/:id', (req, res) => {
gfs.remove({ _id: req.params.id}, (err, gridStore) => {
if (err) {
return res.status(404).json({ err: err });
}
//res.redirect('/');
});
});
const port = 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
@qkreltms
Copy link
Author

qkreltms commented Sep 11, 2018

Two ways to write a file into db (I also uploaded it on my github)

  1. Use Postman

    default
    2.Use web browser

    2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment