如何在JavaScript中打开任何类型的文件并将其保存为字符串(How do i open a file of any type in javascript and have it saved as a string)
所以,当你在文本编辑器中打开任何文件时,无论是图像还是声音文件或代码片段,在文本编辑器中它都会以文本格式显示数据类型,如何使用javascript(在html文档中)打开任何文件并以字符串形式将其保存到变量中,就像在文本编辑器中显示的那样
//something like this var file = getFile(c:/path/location/goes/here); document.write(file); //then it prints the files' text content onto the documentSo, when you open any file in a text editor whether it be an image or a sound file or a peice of code, inside the text editor it comes up with the datatype in text format, how would i use javascript (in a html document) to open any file and save it into a variable as a string, like as presented in a text editor
//something like this var file = getFile(c:/path/location/goes/here); document.write(file); //then it prints the files' text content onto the document最满意答案
你可以使用ajax来加载你的文件,或者如果你想纯js尝试下面的代码
function readBlob() { var files = document.getElementById('files').files; if (!files.length) { alert('Please select a file!'); return; } var file = files[0]; var start = 0; var stop = file.size - 1; var reader = new FileReader(); // If we use onloadend, we need to check the readyState. reader.onloadend = function(evt) { if (evt.target.readyState == FileReader.DONE) { // DONE == 2 document.getElementById('byte_content').textContent = evt.target.result; document.getElementById('byte_range').textContent = ['Read bytes: ', start + 1, ' - ', stop + 1, ' of ', file.size, ' byte file'].join(''); } }; var blob = file.slice(start, stop + 1); reader.readAsBinaryString(blob); }<style> #byte_content { margin: 5px 0; max-height: 100px; overflow-y: auto; overflow-x: hidden; } #byte_range { margin-top: 5px; }</style> <input type="file" id="files" name="file" onchange ="readBlob()" /> <div id="byte_range"></div> <div id="byte_content"></div>You can use ajax to load you file or if you want pure js then try following code snippet
function readBlob() { var files = document.getElementById('files').files; if (!files.length) { alert('Please select a file!'); return; } var file = files[0]; var start = 0; var stop = file.size - 1; var reader = new FileReader(); // If we use onloadend, we need to check the readyState. reader.onloadend = function(evt) { if (evt.target.readyState == FileReader.DONE) { // DONE == 2 document.getElementById('byte_content').textContent = evt.target.result; document.getElementById('byte_range').textContent = ['Read bytes: ', start + 1, ' - ', stop + 1, ' of ', file.size, ' byte file'].join(''); } }; var blob = file.slice(start, stop + 1); reader.readAsBinaryString(blob); }<style> #byte_content { margin: 5px 0; max-height: 100px; overflow-y: auto; overflow-x: hidden; } #byte_range { margin-top: 5px; }</style> <input type="file" id="files" name="file" onchange ="readBlob()" /> <div id="byte_range"></div> <div id="byte_content"></div>
更多推荐
发布评论