如何定位文本 blob 内的内容?
我会长话短说。以下是我用来将 textarea 标记内的文本转换为 .txt 文件的方法:
<textarea id="inputTextToSave"></textarea>
<button onclick="saveTextAsFile()">SAVE</button>
<textarea id="string"></textarea>
<script>
function saveTextAsFile()
{
var textToWrite = document.getElementById("inputTextToSave").value;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain;charset=utf-8'});
document.getElementById("string").innerHTML= textFileAsBlob.txt;
}
</script>
问题是每当我运行该函数并尝试将“inputTextToSave”文本区域中的 blob 内容插入“string”文本区域时,它都不会呈现文本。本质上,我试图定位 blob 内的内容,以便稍后将它们上传到数据库,并且该数据库仅接受 .txt 文件。任何帮助将不胜感激。谢谢!
I'll keep it short. The following is the method I'm using in order to convert the text inside a textarea tag to a .txt file:
<textarea id="inputTextToSave"></textarea>
<button onclick="saveTextAsFile()">SAVE</button>
<textarea id="string"></textarea>
<script>
function saveTextAsFile()
{
var textToWrite = document.getElementById("inputTextToSave").value;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain;charset=utf-8'});
document.getElementById("string").innerHTML= textFileAsBlob.txt;
}
</script>
The issue is whenever I run the function and try to insert the blob content from 'inputTextToSave' textarea in the 'string' textarea, it doesn't render the text. Essentially I'm trying to target the contents inside the blob so that I can later upload them to a database and that db only accepts .txt files. Any help would be appreciated. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用
await textFileAsBlob.text()
将 blob 转换为字符串(不要忘记将函数声明为async
以使用await
方法,因为Blob.text()
方法返回Promise
,而不是实际结果)。示例:
结果:

文档:https://developer.mozilla.org/en-US/docs/Web/API/Blob/text
基于您的代码的代码片段:
Try to use
await textFileAsBlob.text()
to convert blob to string (don't forget to declare your function asasync
to useawait
method, becauseBlob.text()
method returnsPromise
, not the actual result).Example:
Result:

Docs: https://developer.mozilla.org/en-US/docs/Web/API/Blob/text
Code Snippet based on your code: