Skip to content

Commit 29262d1

Browse files
committed
Implement file upload on Express with postgres integration
1 parent 1b965d7 commit 29262d1

File tree

7 files changed

+199
-2
lines changed

7 files changed

+199
-2
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,5 @@
22
.env
33

44
node_modules/
5+
6+
tmp/

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,11 @@ Copy the .env.sample file to a .env file and fill in the missing values
1414
- The .env file should not be checked into the repository, it contains production secrets!
1515
- When starting up, the server will read the database credentials/other info from the .env file.
1616

17-
Run `npm run knex seed:run` to setup the initial database state
17+
Run `npm run knex seed:run` and `npm run knex migrate:latest` to setup the initial database state
1818
Run `npm run start` to start the server
1919

20+
21+
2022
### Setup Postgres
2123
These are some helpful tutorials:
2224
- https://blog.logrocket.com/setting-up-a-restful-api-with-node-js-and-postgresql-d96d6fc892d8/

package-lock.json

Lines changed: 131 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
"main": "src/server.js",
66
"scripts": {
77
"knex": "knex --knexfile ./src/database/knexfile.js",
8-
"start": "node src/server.js"
8+
"start": "node src/server.js",
9+
"setup": "npm run knex seed:run & npm run knex migrate:latest"
910
},
1011
"author": "Vedant Roy",
1112
"license": "ISC",
@@ -14,6 +15,7 @@
1415
"express": "^4.17.1",
1516
"find-config": "^1.0.0",
1617
"knex": "^0.20.10",
18+
"multer": "^1.4.2",
1719
"pg": "^7.18.2"
1820
},
1921
"devDependencies": {}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// NOTE TO DEVS:
2+
// You can also run "npm run knex migrate:down file_migrate.js" to drop the table
3+
// if you run into any issues.
4+
5+
// Adds a files table that has a relation with the user table
6+
exports.up = async (knex) => {
7+
return await knex.schema.createTable('files', (table) => {
8+
table.string('filename');
9+
table.binary('file');
10+
table.string('username');
11+
});
12+
}
13+
14+
// Drops the files table
15+
exports.down = async (knex) => {
16+
return await knex.schema.dropTable('files');
17+
}

src/routes/files.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
const fs = require('fs');
2+
const knex = require('../database/database');
3+
const multer = require('multer');
4+
const router = require('express').Router();
5+
6+
const dir = "\\tmp";
7+
8+
let storage = multer.diskStorage({
9+
// file uploaded is stored in local directory
10+
destination: (req, file, cb) => {
11+
const uploadDir = "\\tmp/uploads/"
12+
// create a new local directory if it did not already exist
13+
fs.exists(uploadDir, exist => {
14+
if (!exist) {
15+
return fs.mkdir(uploadDir, {recursive: true }, err => cb(err, uploadDir));
16+
}
17+
return cb(null, uploadDir);
18+
});
19+
},
20+
filename: (req, file, cb) => {
21+
cb(null, Date.now() + '-' + file.originalname);
22+
}
23+
});
24+
25+
let upload = multer({ storage: storage });
26+
27+
// [base] = localhost:[port]/files
28+
// POST [base]/upload/[a username] attached with a file that has fieldname:'myfile'
29+
// to upload an arbitrary file to the database
30+
router.post('/upload/:user', upload.single('myfile'), async (req, res, next) => {
31+
try {
32+
let username = req.params.user;
33+
let path = req.file.destination + req.file.filename
34+
await knex.raw('INSERT INTO "files" VALUES (?, pg_read_binary_file(?), ?)',
35+
[req.file.filename, path, username]);
36+
res.send("Succesfully uploads file");
37+
} catch (error) {
38+
console.log(error);
39+
}
40+
});
41+
42+
module.exports = router;

src/server.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ const express = require('express')
22
const app = express()
33

44
app.use('/users', require('./routes/users'))
5+
app.use('/files', require('./routes/files'))
56

67
const port = 8080
78
app.listen(port, () => console.log(`Server listening on port ${port}.`))

0 commit comments

Comments
 (0)