J
J
jenya77712018-03-04 14:23:45
Node.js
jenya7771, 2018-03-04 14:23:45

How to get notified when a file upload is completed via socket.io-stream?

Hello, I am uploading a file to the server via socket.io-stream from a browser. In the browser, I can monitor the download process, but how can I run, for example, a function on the server when the download is over?
Here is the server code:

io.of('/admin/tasks/new').on('connection', function (socket) {

  ss(socket).on('video', function(stream, data) {

    let name = String(data.name).trim()
    let title = String(data.name).trim()
    let description = String(data.name).trim()

    if (name && title) {

      let hashName = crypto.randomBytes(40).toString('hex');
      let extension = path.extname(name)
      let pathFile = null

      if (extension === '.mp4') {

        pathFile = `./tasks/videos/${hashName}.${extension}`
      }
      
      if (pathFile) {

        let upload = stream.pipe(fs.createWriteStream(pathFile))

        upload.on('open', () => {

          socket.emit('message', {
            status: 'upload'
          });
        })

        stream.on('error', (streamErr) => {

          socket.emit('message', {
            status: 'message',
            type: 'warn',
            message: 'Во время загрузки файла произошла ошибка'
          });
        });
      } else {

        socket.emit('message', {
          status: 'message',
          type: 'warn',
          message: 'Видео файл неверного формата или повреждён'
        });
      }

    } else {

      socket.emit('message', {
        status: 'message',
        type: 'warn',
        message: 'Ошибка входящих данных'
      });
    }
  });
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Skibin, 2018-03-04
@jenya7771

let writeSream = fs.createWriteStream(pathFile);
let upload = stream.pipe(writeSream);

writeSream.on('finish', () => {
          socket.emit('message', {
            status: 'uploaded'
          });
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question