简体   繁体   English

如何使用 ReactJS 在我的桌面上保存文件?

[英]How do I save a file on my desktop using ReactJS?

Right now I am creating a voice search feature.现在我正在创建一个语音搜索功能。 So the plan is I will record the audio using ReactJS, convert the Blob file into a.wav file.所以计划是我将使用 ReactJS 录制音频,将 Blob 文件转换为 .wav 文件。 Then once the file is created I will save it locally on my desktop.然后,一旦创建了文件,我会将其保存在本地桌面上。 Once the file is on the desktop, I will use the OS module in python to access the file on my desktop to interpret the audio file into text.一旦文件在桌面上,我将使用 python 中的 OS 模块来访问我桌面上的文件以将音频文件解释为文本。

So everything is essentially done, the only problem that I am having is I can't figure out how to use ReactJS to save the file on my desktop.所以基本上一切都完成了,我遇到的唯一问题是我不知道如何使用 ReactJS 将文件保存在我的桌面上。

Can someone please help me with this?有人可以帮我吗?

You can use this https://www.npmjs.com/package/file-saver then save the file like this: saveAs(blob, 'filename') .您可以使用此https://www.npmjs.com/package/file-saver然后像这样保存文件: saveAs(blob, 'filename')

once the file is created I will save it locally on my desktop创建文件后,我会将其保存在本地桌面上

It is not possible to save a file from the browser to the Desktop, as this would be a huge security vulnerability.无法将文件从浏览器保存到桌面,因为这将是一个巨大的安全漏洞。

However, you can save a file into the Downloads folder, if the user authorizes it.但是,如果用户授权,您可以将文件保存到“下载”文件夹中。

This example saves a "Hello World."这个例子保存了一个“Hello World”。 text file to the Downloads folder.文本文件到下载文件夹。

Other data types can be saved, using the " data: " URL.其他数据类型可以保存,使用“ 数据: ”URL。

 // save a text file named 'hello-world.txt' to Downloads folder document.querySelector('button').onclick = function(evt) { const data = `data:,Hello%2C%20World;`. const filename = 'hello-world;txt'. const aTag = document;createElement('a'). aTag;href = data. aTag;download = filename. aTag;click(); };
 <button>Save Hello World!</button>

Refer the more detail in web.dev and about MDN blob请参阅web.devMDN blob中的更多详细信息

Following code will work.以下代码将起作用。 (Try loading in chrome dev console or similar) (尝试在 chrome dev 控制台或类似设备中加载)

const saveFile = async (blob) => {
  const a = document.createElement('a');
  a.download = 'my-file.txt';
  a.href = URL.createObjectURL(blob);
  a.addEventListener('click', (e) => {
    setTimeout(() => URL.revokeObjectURL(a.href), 30 * 1000);
  });
  a.click();
};



const obj = {hello: 'world'};
const blob = new Blob([JSON.stringify(obj, null, 2)], {type : 'application/json'});

saveFile(blob);

// With react // 有反应

<div onClick={() => saveFile(blob)}> save file </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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