保存大量文件

扫码查看
本文介绍了保存大量文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在JS中保存一个未知大小的文件,可能是数GB.数据源是使用mediarecorder捕获的媒体流.

I need to save a file of unknown size, potentially multiple gigabytes, in JS. The data source is a mediastream captured using mediarecorder.

在Chrome中,可以通过将文件系统和文件编写器api与文件系统:URL一起使用,方法是将收到的blob块写入文件条目中,然后设置指向文件url的下载链接.

In Chrome, this can be accomplished using the filesystem and filewriter apis with filesystem: urls by writing blob chunks to a fileentry as they are received, then setting a download link to the file url.

但是,我找不到在Firefox或Edge(无论何时获得mediarecorder)中执行此操作的方法.

However, I cannot find a way to do this in Firefox or Edge (whenever it gets mediarecorder).

推荐答案

这在Firefox中对我有效:

This works for me in Firefox:

navigator.mediaDevices.getUserMedia({ video: true })
  .then(stream => record(stream, 5000)
    .then(recording => {
      stop(stream);
      video.src = link.href = URL.createObjectURL(new Blob(recording));
      link.download = "recording.webm";
      link.innerHTML = "Download blob";
      log("Playing "+ recording[0].type +" recording.");
    })
    .catch(log).then(() => stop(stream)))
  .catch(log);

var record = (stream, ms) => {
  var rec = new MediaRecorder(stream), data = [];
  rec.ondataavailable = e => data.push(e.data);
  rec.start();
  log(rec.state + " for "+ (ms / 1000) +" seconds...");
  var stopped = new Promise((r, e) => (rec.onstop = r, rec.onerror = e));
  return Promise.all([stopped, wait(ms).then(() => rec.stop())])
    .then(() => data);
};

var stop = stream => stream.getTracks().forEach(track => track.stop());
var wait = ms => new Promise(resolve => setTimeout(resolve, ms));
var log = msg => div.innerHTML += "<br>" + msg;
<video id="video" height="120" width="160" autoplay></video>
<a id="link"></a><br>
<div id="div"></div>

用户仍然必须单击下载链接.我还没有尝试过可以得到多大的文件.

A user still has to click the download link. I haven't experimented with how large the file can get.

这篇关于保存大量文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 17:27
查看更多