Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

fabiodurgante

javascipt ler arquivo txt

Recommended Posts

esse script quero ler a variável teste que esta dentro do arquivo dados.txt, depois colocar a variável teste no html, como poderia fazer ????
<script type="text/javascript">
browsername=navigator.appName;
var teste= "65,50"
</script>

<script type="text/javascript"> document.write(teste); </script>

Compartilhar este post


Link para o post
Compartilhar em outros sites
<!DOCTYPE HTML>
<html>
    <head>
    </head>
    <body>
    <br>
    <output id="files"></output>
            <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
    $("#upload").bind("click", function () {
        var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
        if (regex.test($("#fileUpload").val().toLowerCase())) {
            if (typeof (FileReader) != "undefined") {
                var reader = new FileReader();
                reader.onload = function (e) {
                    var table = $("<table />");
                    var rows = e.target.result.split("\n");
                    for (var i = 0; i < rows.length; i++) {
                        var row = $("<tr />");
                        var cells = rows[i].split(".");
                        for (var j = 0; j < cells.length; j++) {
                            var cell = $("<td />");
                            cell.html(cells[j]);
                            row.append(cell);
                        }
                        table.append(row);
                    }
                    $("#dvCSV").html('');
                    $("#dvCSV").append(table);
                }
                reader.readAsText($("#fileUpload")[0].files[0]);
            } else {
                alert("This browser does not support HTML5.");
            }
        } else {
            alert("Please upload a valid CSV file.");
        }
    });
});
</script>
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
<hr />
<div id="dvCSV">
</div>
 
    </body>
</html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo - CSV-to-Table</title>
</head>
<body>
  <div id="inputs" class="clearfix">
    <input type="file" id="files" name="files[]" multiple />
  </div>
  <hr />
  <output id="list">
  </output>
  <hr />
  <table id="contents" style="width:100%; height:400px;" border>
  </table>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
  <script src="http://evanplaice.github.io/jquery-csv/src/jquery.csv.min.js"></script>
  <script>
    $(document).ready(function() {
      if(isAPIAvailable()) {
        $('#files').bind('change', handleFileSelect);
      }
    });
    function isAPIAvailable() {
      // Check for the various File API support.
      if (window.File && window.FileReader && window.FileList && window.Blob) {
        // Great success! All the File APIs are supported.
        return true;
      } else {
        // source: File API availability - http://caniuse.com/#feat=fileapi
        // source: <output> availability - http://html5doctor.com/the-output-element/
        document.writeln('The HTML5 APIs used in this form are only available in the following browsers:<br />');
        // 6.0 File API & 13.0 <output>
        document.writeln(' - Google Chrome: 13.0 or later<br />');
        // 3.6 File API & 6.0 <output>
        document.writeln(' - Mozilla Firefox: 6.0 or later<br />');
        // 10.0 File API & 10.0 <output>
        document.writeln(' - Internet Explorer: Not supported (partial support expected in 10.0)<br />');
        // ? File API & 5.1 <output>
        document.writeln(' - Safari: Not supported<br />');
        // ? File API & 9.2 <output>
        document.writeln(' - Opera: Not supported');
        return false;
      }
    }
    function handleFileSelect(evt) {
      var files = evt.target.files; // FileList object
      var file = files[0];
      // read the file metadata
      var output = ''
          output += '<span style="font-weight:bold;">' + escape(file.name) + '</span><br />\n';
          output += ' - FileType: ' + (file.type || 'n/a') + '<br />\n';
          output += ' - FileSize: ' + file.size + ' bytes<br />\n';
          output += ' - LastModified: ' + (file.lastModifiedDate ? file.lastModifiedDate.toLocaleDateString() : 'n/a') + '<br />\n';
      // read the file contents
      printTable(file);
      // post the results
      $('#list').append(output);
    }
    function printTable(file) {
      var reader = new FileReader();
      reader.readAsText(file);
      reader.onload = function(event){
        var csv = event.target.result;
        var data = $.csv.toArrays(csv);
        var html = '';
        for(var row in data) {
          html += '<tr>\r\n';
          for(var item in data[row]) {
            html += '<td>' + data[row][item] + '</td>\r\n';
          }
          html += '</tr>\r\n';
        }
        $('#contents').html(html);
      };
      reader.onerror = function(){ alert('Unable to read ' + file.fileName); };
    }
  </script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="robots" content="noindex, nofollow">
  <meta name="googlebot" content="noindex, nofollow">
  <title> by bruiz</title>
 
</head>
<body>
 <script>
var leitorDeCSV = new FileReader();
window.onload = function init() {
    leitorDeCSV.onload = leCSV;
}
function pegaCSV(inputFile) {
    var file = inputFile.files[0];
     leitorDeCSV.readAsText(file);
}
function leCSV(evt) {
    var fileArr = evt.target.result.split('\n');
    var strDiv = '<table>';
   
    for (var i=0; i<fileArr.length; i++) {
        strDiv += '<tr>';
        var fileLine = fileArr[i].split('.');
            for (var j=0; j<fileLine.length; j++) {
                strDiv += '<td>'+fileLine[j].trim()+'</td>';
            }
        strDiv += '</tr>';
    }
   
    strDiv += '</table>';
   
    var CSVsaida = document.getElementById('CSVsaida');
        CSVsaida.innerHTML = strDiv;
}
</script>
</head>
    <input type="file" id="inputCSV" onChange="pegaCSV(this)">
    <div id="CSVsaida"></div>
</body>
</html>

Compartilhar este post


Link para o post
Compartilhar em outros sites

assim eu escolho o arquivo e funciona normal porem eu quero abrir o arquivo c:\nova\dados.txt automatico quando abrir a pagina ja carrege esse arquivo no window.onload ??? como poderia fazer onde especifico o nome do arquivo e caminho ????

arquivo dados.txt contem

12

10

8

7

ele abre correto quero colocar 1 linha arquivo na variavel teste1

linha 2 teste2

linha 3 teste3

linha 4 teste4

como poderia fazer isso ???

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.