Writing a serverless method that uploads documents:
Description: One of the most common techniques for uploading
documents involves a form submission from the FrontEnd application. The user
points to a file at a location specified by a folder on her computer and the
client-side script in the frontend reads the file as a stream. When the same
file content needs to be made available to the middleware, HTTP based methods
struggle with the right way to send the data.
The key to send the data is to specify it as a
multipart/form-data. This is the most efficient content-type for sending binary
data to the server. Multiparts means that data is sent to the server in
separate parts. Each of the components may have a different content type, file
name and data. The data are separated from each other by a boundary string.
When a command line tool like curl sends this request , it does so as a
multipart request with a specially formatted POST message body and a series of
parts separated by MIME boundaries
For example,
POST /echo HTTP/1.1
Content-Type: multipart/form-data; boundary=---WD9543A
Content-Length: 100
---WD9543A
Content-Disposition: form-data; name=”user-name”
John
---WD9543A
Content-Disposition: form-data; name=”text-data”;
filename=”user.txt”
Content-Type: text/plain
[Text-Data]
---WD9543A
When the controller receives this request, it can refer
directly to the parts as follows:
Request.body.name
And
Request.file
For example:
Const multer = require(‘multer’)
Const upload = multer({ dest: os.tmpdir()});
Router.post(‘/upload’, upload.single(file), function (req,
res) {
const title = req.body.title;
const file = req.file;
console.log(title);
console.log(file);
res.sendStatus(200);
});
No comments:
Post a Comment