Write file to disk from blob in electron application(在电子应用程序中将文件从 blob 写入磁盘)
问题描述
我正在创建一个 Electron 应用程序,在其中我正在从网络摄像头和桌面记录数据,在记录会话结束时,我想将数据保存到后台的文件中.我不知道如何将数据从 blob 直接写入文件.有什么建议?以下是我当前对 MediaRecord Stop 事件的处理.
I am creating an Electron Application in which I am recording data from webcam and desktop, at the end of the recording session, I want to save the data to a file in the background. I do not know how to write the data from a blob to a file directly. Any suggestions? Below is my current handling for MediaRecord Stop event.
this.mediaRecorder.onstop = (e) => {
var blob = new Blob(this.chunks,
{ 'type' : 'video/mp4; codecs=H.264' });
var fs = require('fs');
var fr = new FileReader();
var data = null;
fr.onload = () => {
data = fr.result;
fs.writeFile("test.mp4", data, err => {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
};
fr.readAsArrayBuffer(blob);
}
推荐答案
您可以使用 FileReader
和 Buffer
来完成.
You can do it using FileReader
and Buffer
.
在渲染器进程中,将事件发送到主进程以将文件与缓冲区一起保存:
In the renderer process, send the event to the main process to save the file with the buffer:
function saveBlob(blob) {
let reader = new FileReader()
reader.onload = function() {
if (reader.readyState == 2) {
var buffer = new Buffer(reader.result)
ipcRenderer.send(SAVE_FILE, fileName, buffer)
console.log(`Saving ${JSON.stringify({ fileName, size: blob.size })}`)
}
}
reader.readAsArrayBuffer(blob)
}
取回确认:
ipcRenderer.on(SAVED_FILE, (event, path) => {
console.log("Saved file " + path)
})
(SAVE_FILE 和 SAVED_FILE 是包含事件名称的静态字符串)
(SAVE_FILE and SAVED_FILE are static strings containing event name)
在主进程中:
ipcMain.on(SAVE_FILE, (event, path, buffer) => {
outputFile(path, buffer, err => {
if (err) {
event.sender.send(ERROR, err.message)
} else {
event.sender.send(SAVED_FILE, path)
}
})
})
outputFile 来自 'fs-extra'一个>
outputFile is from 'fs-extra'
首选在主进程中处理节点操作.请参阅 Electron 安全建议.
Handling node operations in main process is preferred. See Electron Security suggestions.
如果你不想使用主进程,你可以使用 'electron-remote' 创建后台进程来写入文件.此外,您可以在后台进程中调用 ffmpeg
将文件压缩/编码为不同的格式.
If you do want to not use main process, you can use 'electron-remote' to create background processes to write the file. Additionally, you can invoke ffmpeg
in the background process to compress/encode the file into different format.
这篇关于在电子应用程序中将文件从 blob 写入磁盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在电子应用程序中将文件从 blob 写入磁盘
基础教程推荐
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 在for循环中使用setTimeout 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 动态更新多个选择框 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01