如何使用JavaScript将 huangapple 117266文章 0评论 2023年3月9日 18:55:11go评论85阅读模式 英文: How can I get the actual file in an <input type=file>, to be displayed in the <textarea> tag with JavaScript? 问题 以下是翻译好的代码部分: let textfile = document.getElementById('file'); let textarea = document.getElementById('compose'); console.log(textarea); textfile.addEventListener('change', (e) => { let fil = e.target.files[0]; if (fil) { let reader = new FileReader(); reader.readAsDataURL(fil); } textarea.value = fil; }); 如果您需要关于代码的进一步解释或帮助,请随时提出。 英文: I have an input tag with type=file and I want to take the data it selects to display inside a textarea tag. I do not want to display just the file title but the entire file. Like how uploading attachments to emails before they are sent works. How do I do this with javascript? There is no backend or server-side code in this work yet. I have tried to change the value but it only displayed the object type of the file to the textarea let textfile = document.getElementById('file') let textarea = document.getElementById('compose') console.log(textarea); textfile.addEventListener('change', (e) =>{ let fil = e.target.files[0]; if(fil){ let reader = new FileReader(); reader.readAsDataURL(fil); } textarea.value = fil }) 答案1 得分: 1 以下是翻译好的部分: 使用FileReader API,它将读取文件的内容,然后您应该添加onload函数,以便在FileReader加载后才获取数据,然后将textarea元素的值属性设置为文件的内容。 let textfile = document.getElementById('file'); let textarea = document.getElementById('compose'); textfile.addEventListener('change', (e) => { let file = e.target.files[0]; if (file) { let reader = new FileReader(); reader.readAsText(file); reader.onload = function(e) { textarea.value = e.target.result; } } }); <div> <input type="file" id="file"> </div> <div> <textarea id="compose" rows="5" cols="50"></textarea> </div> 英文: Here is an example: Using the FileReader API, So it will read the contents of the file and then you should add onload function to get the data only after the load of FileReader, then set the value property of the textarea element to the contents of the file. <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> let textfile = document.getElementById('file'); let textarea = document.getElementById('compose'); textfile.addEventListener('change', (e) => { let file = e.target.files[0]; if (file) { let reader = new FileReader(); reader.readAsText(file); reader.onload = function(e) { textarea.value = e.target.result; } } }); <!-- language: lang-html --> <div> <input type="file" id="file"> </div> <div> <textarea id="compose" rows="5" cols="50"></textarea> </div> <!-- end snippet --> 通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。 点赞 https://go.coder-hub.com/75683630.html 复制链接 复制链接