Hello, this is a simple project for testing my app in Android, but is very useful for work in other app. In this case is using for upload a CSV file, but is very simple change the type of file
This code is available on GitHub
Requirement:
- Node JS >= 12
- Nodemon
First the node app is created:
npm init (Change the main to app.js)
Second, install dependencie:
npm i ---save express npm i ---save multer npm i ---save cors
The magic or helper is multer, with this library we can upload different files. Express is a simple web server and the cors is to avoid problems.
Initialize all const for work
const multer = require('multer'); const express = require('express'); const cors = require('cors'); const path = require('path'); const fs = require('fs'); const app = express(); const port = 3000;
Now is necessary to create a folder for upload all CSV, in this case is called "uploads"
let uploads = __dirname + '/uploads'; if (!fs.existsSync(uploads)) { console.log('trying for create the directory "upload"'); fs.mkdirSync(uploads); }
The nextstep is create the function for storage, filter and initialize the multer:
global.__basedir = __dirname; const storage = multer.diskStorage({ destination: (req, file, callback) => { callback(null, __basedir + '/uploads/'); }, filename: (req, file, callback) => { callback(null, file.fieldname + "-" + Date.now() + "-" + file.originalname); } }); const filterCSV = (req, file, callback) => { let ext = path.extname(file.originalname); if(ext === '.csv') { callback(null, true); } else { callback('File format is not a CSV', false); } } const upload = multer({ storage: storage, fileFilter: filterCSV });
For work with other type of file is necesary change the value on:
const filterCSV = (req, file, callback) => { let ext = path.extname(file.originalname); if(ext === '.csv') { callback(null, true); } else { callback('File format is not a CSV', false); } }
for example, is necessary to evaluate ext == '.pdf' or another extension for work with your code. Rename the function to make it look better.
Then we all declare all function for work with express:
app.use(cors()) app.post('/upload/', upload.single('uploadFile'), (req, res) => { try{ if(req.file == undefined) { res.status(400).send({ message: "Please upload a CSV file: " }); } else { res.status(200).send({ message: "File Upload: " }); } } catch(error) { res.status(500).send({ message: "Could not upload the file: " + req.file.originalname }); } }); app.get('/upload/', (req, res) => { res.send("Hello from Node") ; }); app.listen(port, '0.0.0.0', () => { console.log(`App listening port ${port}`); });
On the line in the method POST is declare an argument for the callback "upload.single('uploadFile')", the "uploadFile" is the name of the input file.
Testing:
For run the app
nodemon dev or node app (for this case, if the app is crashed, is necessary back to run the app)
That's all folks
Comentarios
Publicar un comentario