Foros del Web » Programando para Internet » Javascript »

[SOLUCIONADO] ¿Cómo guardar un TXT en Javascript?

Estas en el tema de ¿Cómo guardar un TXT en Javascript? en el foro de Javascript en Foros del Web. Hola a todos, quisiera saber si es posible en Javascript y pulsando un botón, coger el valor de un textarea y que se abriera un ...
  #1 (permalink)  
Antiguo 13/10/2014, 01:58
 
Fecha de Ingreso: julio-2010
Mensajes: 298
Antigüedad: 13 años, 9 meses
Puntos: 8
¿Cómo guardar un TXT en Javascript?

Hola a todos, quisiera saber si es posible en Javascript y pulsando un botón, coger el valor de un textarea y que se abriera un cuadro de diálogo que permitiera guardar el contenido de dicho textarea en un fichero de texto en el sitio que decidiera el usuario. Es esto posible? El navegador puede ser IE, CHROME, FIREFOX, ... Evidentenmente, ya recae en el usuario escoger una carpeta en la que tenga eprmisos para guardar el fichero.

Alguna idea?

Muchas gracias
  #2 (permalink)  
Antiguo 13/10/2014, 04:07
Avatar de HackID1  
Fecha de Ingreso: febrero-2013
Ubicación: En Update
Mensajes: 492
Antigüedad: 11 años, 2 meses
Puntos: 17
Respuesta: ¿Cómo guardar un TXT en Javascript?

Hola!!!.

Si se puede hacer esto en JScript usando Blob HTML5.

Un objeto Blob representa un objeto de fichero de datos brutos, inmutables. Blobs representan datos que no son necesariamente en un formato JavaScript-nativa. La interfaz del archivo se basa en Blob, heredando funcionalidad blob y ampliarlo para soportar archivos en el sistema del usuario. El objeto Blob y la interfaz de archivo son tanto una parte de la WebAPI

Y ahora. Creamos un HTML con el formulario y el textarea.

Código HTML:
Ver original
  1. <!DOCTYPE html>
  2. <head></title>Guardar Textarea</title>
  3. <script type="text/javascript" src="guardar_textarea.js"></script>
  4. </head>
  5.  
  6.   <tr><td>Escriba el texto:</td></tr>
  7.   <tr>
  8.         <td colspan="3">
  9.             <textarea id="inputTextToSave" style="width:512px;height:256px"></textarea>
  10.         </td>
  11.     </tr>
  12.     <tr>
  13.    
  14.     <!-- A button to call out JavaScript Function -->
  15.         <td><button onclick="saveTextAsFile()">Save Text to File</button></td>
  16.     </tr>
  17.  
  18.  
  19.   </body>
  20. </html>

Ahora el Fichero que procesará el textarea y lo guardara en un archivo .txt

El nombre del archivo Js sería: guardar_textarea.js

Código Javascript:
Ver original
  1. function saveTextAsFile()
  2. {      
  3. // grab the content of the form field and place it into a variable
  4.     var textToWrite = document.getElementById("inputTextToSave").value;
  5. //  create a new Blob (html5 magic) that conatins the data from your form feild
  6.     var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
  7. // Specify the name of the file to be saved
  8.     var fileNameToSaveAs = "myNewFile.txt";
  9.    
  10. // Optionally allow the user to choose a file name by providing
  11. // an imput field in the HTML and using the collected data here
  12. // var fileNameToSaveAs = txtFileName.text;
  13.  
  14. // create a link for our script to 'click'
  15.     var downloadLink = document.createElement("a");
  16. //  supply the name of the file (from the var above).
  17. // you could create the name here but using a var
  18. // allows more flexability later.
  19.     downloadLink.download = fileNameToSaveAs;
  20. // provide text for the link. This will be hidden so you
  21. // can actually use anything you want.
  22.     downloadLink.innerHTML = "My Hidden Link";
  23.    
  24. // allow our code to work in webkit & Gecko based browsers
  25. // without the need for a if / else block.
  26.     window.URL = window.URL || window.webkitURL;
  27.          
  28. // Create the link Object.
  29.     downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
  30. // when link is clicked call a function to remove it from
  31. // the DOM in case user wants to save a second file.
  32.     downloadLink.onclick = destroyClickedElement;
  33. // make sure the link is hidden.
  34.     downloadLink.style.display = "none";
  35. // add the link to the DOM
  36.     document.body.appendChild(downloadLink);
  37.    
  38. // click the new link
  39.     downloadLink.click();
  40. }
  41.  
  42. function destroyClickedElement(event)
  43. {
  44. // remove the link from the DOM
  45.     document.body.removeChild(event.target);
  46. }
  47.  
  48. // EOF

El código lo use hace ya tiempo pero funciona perfectamente para lo que quieres realizar.
Por defecto guarda las descargas igual que cuando descargas algo de Internet, en la carpeta Descargas.

Saludos!!!.
__________________
Puntuar +1 es buena forma de dar las gracias. :P
Your Time is limited, so don't waste it living someone else´s life.
Por: HackID1
  #3 (permalink)  
Antiguo 16/10/2014, 02:17
 
Fecha de Ingreso: julio-2010
Mensajes: 298
Antigüedad: 13 años, 9 meses
Puntos: 8
Respuesta: ¿Cómo guardar un TXT en Javascript?

Genial HackID1,
Ha sido de mucha ayuda y funciona perfectamente.

Muchas gracias
  #4 (permalink)  
Antiguo 18/10/2014, 09:07
Avatar de HackID1  
Fecha de Ingreso: febrero-2013
Ubicación: En Update
Mensajes: 492
Antigüedad: 11 años, 2 meses
Puntos: 17
Respuesta: ¿Cómo guardar un TXT en Javascript?

Perfecto que te haya funcionado el script, un saludo !.
__________________
Puntuar +1 es buena forma de dar las gracias. :P
Your Time is limited, so don't waste it living someone else´s life.
Por: HackID1
  #5 (permalink)  
Antiguo 18/10/2014, 12:44
Avatar de IsaBelM
Colaborador
 
Fecha de Ingreso: junio-2008
Mensajes: 5.032
Antigüedad: 15 años, 10 meses
Puntos: 1012
Respuesta: ¿Cómo guardar un TXT en Javascript?

yo prefiero FileReader() a URL.createObjectURL() por que en futuras versiones de navegadores que hoy en día no aceptan ni uno ni otro FileReader() tendrá cobertura antes

Cita:
function descargarArchivo(nombreArchivo) {

var texto = document.getElementById('txtArea').value;
var contenidoEnBlob = new Blob([texto], {type: 'text/plain'});
var lector = new FileReader();

lector.onload = function(event) {

var guardar = document.createElement('a');
guardar.href = event.target.result;
guardar.target = '_blank';
guardar.download = nombreArchivo || 'archivo.dat';
var clicEvent = new MouseEvent('click', {
'view': window,
'bubbles': false,
'cancelable': true
});

guardar.dispatchEvent(clicEvent);
};

lector.readAsDataURL(contenidoEnBlob);
};

window.onload = function() {

document.getElementById('boton').addEventListener( 'click', function () {

descargarArchivo('archivo.txt');

}, false);
}

<form>
<textarea id="txtArea" style="width:100px;height:50px"></textarea>
<br />
<button type="button" id="boton">Guardar como Archivo</button>
</form>
__________________
if(ViolenciaDeGénero) {alert('MUJER ASESINADA');}
  #6 (permalink)  
Antiguo 14/08/2015, 11:54
 
Fecha de Ingreso: agosto-2015
Mensajes: 1
Antigüedad: 8 años, 8 meses
Puntos: 0
Respuesta: ¿Cómo guardar un TXT en Javascript?

hola no me funciona, podrian ayudarme este el codigo que utlizo:

<!DOCTYPE html>
<html>

<script type="text/javascript">
function descargarArchivo(nombreArchivo) {

function saveTextAsFile()
{
// grab the content of the form field and place it into a variable
var textToWrite = document.getElementById("inputTextToSave").value;
// create a new Blob (html5 magic) that conatins the data from your form feild
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
// Specify the name of the file to be saved
var fileNameToSaveAs = "myNewFile.txt";

// Optionally allow the user to choose a file name by providing
// an imput field in the HTML and using the collected data here
var fileNameToSaveAs = txtFileName.text;

// create a link for our script to 'click'
var downloadLink = document.createElement("a");
// supply the name of the file (from the var above).
// you could create the name here but using a var
// allows more flexability later.
downloadLink.download = fileNameToSaveAs;
// provide text for the link. This will be hidden so you
// can actually use anything you want.
downloadLink.innerHTML = "My Hidden Link";

// allow our code to work in webkit & Gecko based browsers
// without the need for a if / else block.
window.URL = window.URL || window.webkitURL;

// Create the link Object.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
// when link is clicked call a function to remove it from
// the DOM in case user wants to save a second file.
downloadLink.onclick = destroyClickedElement;
// make sure the link is hidden.
downloadLink.style.display = "none";
// add the link to the DOM
document.body.appendChild(downloadLink);

// click the new link
downloadLink.click();
}

function destroyClickedElement(event)
{
// remove the link from the DOM
document.body.removeChild(event.target);
}
</sccript>

<script type="text/javascript" src="guardar_textarea.js"></script>
</head>
<body>

<table>
<tr><td>Escriba el texto:</td></tr>
<tr>
<td colspan="3">
<textarea id="inputTextToSave" style="width:512px;height:256px"></textarea>
</td>
</tr>
<tr>
<td><button onclick="saveTextAsFile()">Save Text to File</button></td>
</tr>

</table>



</form>
</body>
</html>

alguna idea, muchas gracias

Etiquetas: fichero, txt
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Tema Cerrado




La zona horaria es GMT -6. Ahora son las 09:05.