简体   繁体   中英

Sending videos from the client to the server

I recently read about the File API which allows the client to use files from the file system in the website.

I did all the stuff of adding the file input tag and reading the file and everything.

I read the file as ArrayBuffer using a FileReader and used a Uint8Array view on it, then I send the view to the server.

I tried it with txt, pdf and images and it worked fine. But when to use it with video files the computer lagged that and I didn't even wait and closed the browser!

Here's the code

Why did the lag happen with video files and is there a way to avoid it?!

I gone through the code, you are appending the read data pushed into the array which may be the reason why it lags.

You need to upload the video in chunks. To make a chunk of file you choose, you can take a look here HTML5 file reader api

  function readBlob(opt_startByte, opt_stopByte) {
    var files = document.getElementById('files').files;
    if (!files.length) {
      alert('Please select a file!');
      return;
    }

    var file = files[0];
    var start = parseInt(opt_startByte) || 0;
    var stop = parseInt(opt_stopByte) || file.size - 1;

    var reader = new FileReader();

    // If we use onloadend, we need to check the readyState.
    reader.onloadend = function(evt) {
      if (evt.target.readyState == FileReader.DONE) { // DONE == 2
        document.getElementById('byte_content').textContent = evt.target.result;
        document.getElementById('byte_range').textContent = 
            ['Read bytes: ', start + 1, ' - ', stop + 1,
             ' of ', file.size, ' byte file'].join('');
      }
    };

    var blob = file.slice(start, stop + 1);
    reader.readAsBinaryString(blob);
    }

    document.querySelector('.readBytesButtons')
      .addEventListener('click', function(evt) {
    if (evt.target.tagName.toLowerCase() == 'button') {
      var startByte = evt.target.getAttribute('data-startbyte');
      var endByte = evt.target.getAttribute('data-endbyte');
      readBlob(startByte, endByte);
    }
  }, false);

You need to modify according to your requirements. Here when you get the chunk, make a request to upload it or play it.

Also you can play with you video file here Upload your Video file here to test

Hope this solves your problem. To get this working you need to handle the chunks properly on the backend as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM