First, the backend part.
Full code: https://github.com/aleksvp2017/uploadfile
Using:
Node.js: the runtime environment;
Express: HTTP server;
Cors: avoid cross-origin problems while calling localhost endpoints from browsers;
Multer: process multipart/form-data, in other words, extract the file from the HTTP post;
Streamifier: transform buffer data to stream.
We use multer to extract file. It always expects an array of files and the name of the parameter must match the one used in the fronted. It will be available on req.file, which is a array. So, as we're sending only one file, it is going to an object on req.files[0]. One of its fields is a buffer.
We use streamifier to convert this buffer into a stream. From there you can do pretty much anything you want.
In the end, we're just returning a response with a success message.
var express = require('express') var app = express() var cors = require('cors') app.use(cors()) const multer = require("multer") //fileuploaded must match the parameter name in the front-end, the one set in formData app.post("/endpoint", multer().array("fileuploaded"), function (req, res) { console.log("files:", req.files); const streamifier = require('streamifier'); var stream = streamifier.createReadStream(req.files[0].buffer) res.status(200).json({ message: 'File received' }) }); let port = 3001 app.listen(port, () => { console.log('Server up and listening at ' + port)})
Now, the frontend.
Full code: https://github.com/aleksvp2017/uploadfile-ui
Using:
Vue / Vuetify: to construct de UI;
Vue-resouce: to call HTTP endpoints.
I choose to use Vue / Vuetify only because I'm working on a project with those, but to send the file you can use a HTML simple form. In the repository you will find a file named form.html as an example.
With Vuetify all you have to do is use v-file-input component to receive the file from the user. Then you call the end point, using vue-resource, encapsulating the file in a form data. This way, there is no need to set any headers. The only detail here is that the parameter name used in formData must match the one used in the backend.
The code that matters is this one:
let formData = new FormData() //this parameter must match the one used by multer in the backend formData.append('fileuploaded', this.fileuploaded) this.$http.post('http://localhost:3001/endpoint', formData). then((response) => { console.log(response) message(this, true, response.body.message, 'success') }).catch(error => message(this, true, error, 'error'))
Pretty simple, uh?
Comments