Write file to disk from blob in electron application

不羁的心 提交于 2019-12-05 08:27:25

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)
}

Get back the confirmation:

ipcRenderer.on(SAVED_FILE, (event, path) => {
    console.log("Saved file " + path)
})

(SAVE_FILE and SAVED_FILE are static strings containing event name)

and in the main process:

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 is from 'fs-extra'

Handling node operations in main process is preferred. See Electron Security suggestions.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!