Tôi muốn hiển thị nội dung của tệp đã tải lên trong HTML, tôi chỉ có thể tải lên một tệp văn bản. Ví dụ của tôi.html:
Please specify a file, or a set of files:
Làm cách nào tôi có thể hiển thị nội dung của bất kỳ tệp văn bản được tải lên nào trong TextArea được hiển thị bên dưới?
Đã hỏi ngày 31 tháng 7 năm 2015 lúc 13:00Jul 31, 2015 at 13:00
1
Tôi đã đến đây từ Google và rất ngạc nhiên khi thấy không có ví dụ làm việc.
Bạn có thể đọc các tệp với API Filereader với hỗ trợ trình duyệt chéo tốt.
const reader = new FileReader[]
reader.onload = event => console.log[event.target.result] // desired file content
reader.onerror = error => reject[error]
reader.readAsText[file] // you could also read images and other binaries
Xem ví dụ đầy đủ làm việc dưới đây.
Đã trả lời ngày 24 tháng 5 năm 2017 lúc 14:55May 24, 2017 at 14:55
Teralesteralesterales
2.85621 huy hiệu bạc33 huy hiệu đồng21 silver badges33 bronze badges
2
Đây là một cách:
HTML
Select a File to Load:
Load Selected File
JavaScript
function loadFileAsText[]{
var fileToLoad = document.getElementById["fileToLoad"].files[0];
var fileReader = new FileReader[];
fileReader.onload = function[fileLoadedEvent]{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById["inputTextToSave"].value = textFromFileLoaded;
};
fileReader.readAsText[fileToLoad, "UTF-8"];
}
Ehsant
2.0793 Huy hiệu vàng28 Huy hiệu bạc 30 Huy hiệu Đồng3 gold badges28 silver badges30 bronze badges
Đã trả lời ngày 13 tháng 11 năm 2016 lúc 23:33Nov 13, 2016 at 23:33
Ứng dụngapp
2813 Huy hiệu bạc3 Huy hiệu đồng3 silver badges3 bronze badges
3
Thử cái này.
HTML
Please specify a file, or a set of files:
JavaScript
function myFunction[]{
var x = document.getElementById["myFile"];
var txt = "";
if ['files' in x] {
if [x.files.length == 0] {
txt = "Select one or more files.";
} else {
for [var i = 0; i < x.files.length; i++] {
txt += [i+1] + ". file";
var file = x.files[i];
if ['name' in file] {
txt += "name: " + file.name + "";
}
if ['size' in file] {
txt += "size: " + file.size + " bytes ";
}
}
}
}
else {
if [x.value == ""] {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById["demo"].innerHTML = txt;
}
Ehsant
2.0793 Huy hiệu vàng28 Huy hiệu bạc 30 Huy hiệu ĐồngJul 31, 2015 at 13:20
Đã trả lời ngày 13 tháng 11 năm 2016 lúc 23:33Shrinivas Pai
Ứng dụng4 gold badges26 silver badges55 bronze badges
4