A
A
Al2016-05-12 02:39:38
Node.js
Al, 2016-05-12 02:39:38

How to implement uploading files to the server with a progress bar?

I have a nodejs application with express 4.x. Something like this at the moment I am uploading files from the form to the server:

var express = require("express");
    var router = express.Router();
    var multipart = require("connect-multiparty");
    var multipartMiddleware = multipart();
    var ResourcesController = require("src/resources/resourcesController");
    
    router.post("/saveResource", multipartMiddleware, function(req, res) {
    	var instance = new ResourcesController(res,req);
    	instance.saveResource();
    });
    
    module.exports = router;

Thanks to connect-multiparty , you can get transferred files in req.files and then do something with them.
But, I want to show the user the progress of uploading files to the server, for this I will use sockets. For example, when router.post("/saveResource" ... the server emits an event with info, the client draws it beautifully accordingly. It was at this step that I stumbled, because what gets into req.files is already loaded to a temporary folder on the server, and I need to somehow intercept these files at the stage of uploading to the server, make a ReadStream and in .on('data')emit an event with info to the client via a socket. How to do this, I haven’t figured it out yet, maybe there is something like connect-multiparty but with the ability to output progress to a stream or some other way?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Wolf, 2016-05-12
@Sanu0074

Try using the lower level library that connect-multiparty is based on. Somehow there is progress :)
https://github.com/andrewrk/node-multiparty

var form = new multiparty.Form();
form.on('progress', function(bytesReceived, bytesExpected) {
   socket.emit('received', (bytesReceived / bytesExpected).toFixed(2) * 100);
});

V
Vitaly Sivkov, 2016-05-12
@Sivkoff

About a year ago I performed a similar task, although Node was version 0.12.
Used socket-io.stream and progress-stream , worked great. True, I had the task of streaming a file from the browser of one user to the browser of another with progress indication on both sides. But I think you should too.

E
Eugene, 2016-05-12
@Nc_Soft

Why not do it through nginx?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question