Skip to content

Instantly share code, notes, and snippets.

@m99coder
Last active December 2, 2022 12:30
Show Gist options
  • Save m99coder/bc9120da4c54fa947466ce1e34c93f3a to your computer and use it in GitHub Desktop.
Save m99coder/bc9120da4c54fa947466ce1e34c93f3a to your computer and use it in GitHub Desktop.
Node.js: Proxy multipart/form-data file upload to application/octet-stream REST API call
#!/usr/bin/env node
// dependencies
const https = require('https');
const express = require('express');
const multer = require('multer');
// app
const app = express();
const storage = multer.memoryStorage();
const upload = multer({storage: storage});
// form
app.get('/', (req, res) => {
res.header('Content-Type', 'text/html');
res.status(200).send(
`<form method="post" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" value="Upload">
</form>`
);
});
// upload
app.post('/', upload.single('image'), (req, res) => {
let options = {
host: 'upload.api.com',
method: 'POST',
path: '/upload',
headers: {
'Authorization': 'Bearer my-access-token',
'Content-Type': 'application/octet-stream',
'Content-Length': req.file.buffer.length
}
};
const request = https.request(options, response => {
// NOTE: rewrite headers if needed
res.writeHead(response.statusCode, response.headers);
response.pipe(res);
});
request.write(req.file.buffer);
request.end();
});
// start server
let port = process.env.PORT || 4000;
app.listen(port, () => {
console.log(`Upload API listening on port ${port}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment