Skip to content

Instantly share code, notes, and snippets.

@TRomesh
Forked from abachuk/NodeFileUpload.js
Created May 25, 2017 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TRomesh/ad792b12ba8b8adddb05e7786423b6b0 to your computer and use it in GitHub Desktop.
Save TRomesh/ad792b12ba8b8adddb05e7786423b6b0 to your computer and use it in GitHub Desktop.
import express from 'express';
import axios from 'axios';
import multer from 'multer';
const app = express();
/**
... express.js boilerplate
routes, middlewares, helpers, loggers, etc
**/
// configuring Multer to use files directory for storing files
// this is important because later we'll need to access file path
const storage = multer.diskStorage({
destination: './files',
filename(req, file, cb) {
cb(null, `${new Date()}-${file.originalname}`);
},
});
const upload = multer({ storage });
// express route where we receive files from the client
// passing multer middleware
app.post('/files', upload.single('file'), (req, res) => {
const file = req.file; // file passed from client
const meta = req.body; // all other values passed from the client, like name, etc..
// send the data to our REST API
axios({
url: `https://api.myrest.com/uploads`,
method: 'post',
data: {
file,
name: meta.name,
},
})
.then(response => res.status(200).json(response.data.data))
.catch((error) => res.status(500).json(error.response.data));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment