Skip to content

Instantly share code, notes, and snippets.

@casamia918
Last active February 19, 2021 10:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save casamia918/3966de2dcafeb8aa8c6dcedf108c3041 to your computer and use it in GitHub Desktop.
Save casamia918/3966de2dcafeb8aa8c6dcedf108c3041 to your computer and use it in GitHub Desktop.
nodejs file upload proxy server & storage server example code
// proxy server
// ref: https://gist.github.com/m99coder/bc9120da4c54fa947466ce1e34c93f3a
// belows are only upload related code
const http = require('http');
const multer = require('multer');
const upload = multer({
storage: multer.memoryStorage(),
limits: {}
})
router.post('/user/profile-image', upload.single('image-file'), function (req, res, next) {
const request = http.request({
host: 'localhost',
port: 'storage-server-port',
method: 'post',
path: '/upload',
headers: {
'Authorization': 'token',
'Content-Type': 'appllication/octect-stream',
'Content-Length': req.file.buffer.length,
}
}, response => {
// The origianal reference code just pipe response to res. Like this: response.pipe(res)
// If you wanna do something in the proxy server after upload is done,
// create 'data' event handler at response of request to storage server. see below.
// request, response : http object connected with storage server
// req, res: express object connected with front-end
let imgServerSuccess = true, failMessage = '';
response.on('finish', () => {
res.writeHead(response.statusCode, response.headers)
res.send({ success: imgServerSuccess, message: failMessage})
})
response.on('data', chunk => {
const { success, filePath } = JSON.parse(chunk);
imgServerSuccess = success;
// Do something
// console.log(success, filePath)
})
})
request.write(req.file.buffer);
request.end();
})
// storage server
// belows are only upload handling part code
const bodyParser = require('body-parser');
const rawParser = bodyParser.raw()
function isAuthorized(req, res, next) {
if (req.get('Authorization') === 'token') {
next();
} else {
next(new Error('Your are not authorized'));
}
}
router.post('/upload', isAuthorized, rawParser, function (req, res, next) {
console.log('file incoming!!');
const uploadPath = path.resolve(__dirname, '../uploads', 'testname.jpg');
const ws = fs.createWriteStream(uploadPath);
ws.on('finish', () => {
res.json({ success: true, filePath: uploadPath })
res.end();
})
req.pipe(ws);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment