2012-12-03 59 views
6

Czy można zapisać textinput (lokalnie) z formularza do pliku tekstowego, a następnie otworzyć ten dokument, aby użyć go później?Czy mogę zapisać dane wejściowe z formularza na .txt w HTML, używając JAVASCRIPT/jQuery, a następnie użyć?

Wystarczy użyć HTML, javascript i jQuery. Brak baz danych lub php.

/W

+3

podejście błędne. Nawet jeśli to możliwe, nie jest to celem stron internetowych. –

+0

Odpowiedź na to pytanie zależy od tego, czy chodzi o stronę serwera, czy po stronie klienta: –

Odpowiedz

-1

Odpowiedź brzmi TAK

<html> 
<head> 
</head> 
<body> 
<script language="javascript"> 
function WriteToFile() 
{ 
var fso = new ActiveXObject("Scripting.FileSystemObject"); 
var s = fso.CreateTextFile("C:\\NewFile.txt", true); 
var text=document.getElementById("TextArea1").innerText; 
s.WriteLine(text); 
s.WriteLine('***********************'); 
s.Close(); 
} 
</script> 

<form name="abc"> 
<textarea name="text">FIFA</textarea> 
<button onclick="WriteToFile()">Click to save</Button> 
</form> 

</body> 
</html> 
+7

... a to zadziała tylko w przypadku InternetExplorer i tylko wtedy, gdy pozwalają na to ustawienia zabezpieczeń. – Pointy

+1

Widzę tylko ActiveXObject; Rozumiem, że to tylko IE? –

+0

poprawne! i pamiętaj, że nie jest to bezpieczne, aby umożliwić tę funkcjonalność – topcat3

1

Można użyć localStorage aby zapisać dane do późniejszego wykorzystania, ale nie można zapisać do pliku użyciu JavaScript (w przeglądarce).

Aby być wyczerpującym: Nie można zapisać czegoś do pliku przy użyciu JavaScript w przeglądarce, ale using HTML5, można odczytać pliki.

0

Nie można zapisać go jako pliku lokalnego bez użycia logiki po stronie serwera. Ale jeśli to pasuje do twoich potrzeb, możesz zajrzeć do lokalnego magazynu html5 lub nas wtyczki javascript jako jStorage

11

Możliwe jest zapisanie tylko wtedy, gdy użytkownik zezwoli na zapisanie go tak jak pobranie i musi otworzyć go ręcznie, jedynym problemem jest zasugerowanie nazwy, mój przykładowy kod zasugeruje nazwę tylko dla Google Chome i tylko jeśli użyjesz łącza zamiast przycisku z powodu atrybutu download.

Potrzebujesz tylko base64 encode library i JQuery do łatwych rzeczy.

<!DOCTYPE html> 
<html> 
<head><title></title> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> 
<script type="text/javascript" src="base64.js"></script> 
<script type="text/javascript"> 
<!-- 
// This will generate the text file content based on the form data 
function buildData(){ 
    var txtData = "Name: "+$("#nameField").val()+ 
      "\r\nLast Name: "+$("#lastNameField").val()+ 
      "\r\nGender: "+($("#genderMale").is(":checked")?"Male":"Female"); 

    return txtData; 
} 
// This will be executed when the document is ready 
$(function(){ 
    // This will act when the submit BUTTON is clicked 
    $("#formToSave").submit(function(event){ 
     event.preventDefault(); 
     var txtData = buildData(); 
     window.location.href="data:application/octet-stream;base64,"+Base64.encode(txtData); 
    }); 

    // This will act when the submit LINK is clicked 
    $("#submitLink").click(function(event){ 
     var txtData = buildData(); 
     $(this).attr('download','sugguestedName.txt') 
      .attr('href',"data:application/octet-stream;base64,"+Base64.encode(txtData)); 
    }); 
}); 
//--> 
</script> 
</head> 
<body> 
<form method="post" action="" id="formToSave"> 
    <dl> 
     <dt>Name:</dt> 
     <dd><input type="text" id="nameField" value="Sample" /></dd> 
     <dt>Last Name:</dt> 
     <dd><input type="text" id="lastNameField" value="Last Name" /></dd> 
     <dt>Gender:</dt> 
     <dd><input type="radio" checked="checked" name="gender" value="M" id="genderMale" /> 
      Male 
      <input type="radio" checked="checked" name="gender" value="F" /> 
      Female 
    </dl> 
    <p><a href="javascript://Save as TXT" id="submitLink">Save as TXT</a></p> 
    <p><button type="submit"><img src="http://www.suttonrunners.org/images/save_icon.gif" alt=""/> Save as TXT</button></p> 
</form> 
</body> 
</html> 
0

to będzie działać zarówno obciążenia i zapisać plik w formacie TXT ze strony HTML z zapisać jako wybór

<html> 
<body> 

<table> 
    <tr><td>Text to Save:</td></tr> 
    <tr> 
     <td colspan="3"> 
      <textarea id="inputTextToSave" cols="80" rows="25"></textarea> 
     </td> 
    </tr> 
    <tr> 
     <td>Filename to Save As:</td> 
     <td><input id="inputFileNameToSaveAs"></input></td> 
     <td><button onclick="saveTextAsFile()">Save Text to File</button></td> 
    </tr> 
    <tr> 
     <td>Select a File to Load:</td> 
     <td><input type="file" id="fileToLoad"></td> 
     <td><button onclick="loadFileAsText()">Load Selected File</button><td> 
    </tr> 
</table> 

<script type="text/javascript"> 

function saveTextAsFile() 
{ 
    var textToSave = document.getElementById("inputTextToSave").value; 
    var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"}); 
    var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob); 
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value; 

    var downloadLink = document.createElement("a"); 
    downloadLink.download = fileNameToSaveAs; 
    downloadLink.innerHTML = "Download File"; 
    downloadLink.href = textToSaveAsURL; 
    downloadLink.onclick = destroyClickedElement; 
    downloadLink.style.display = "none"; 
    document.body.appendChild(downloadLink); 

    downloadLink.click(); 
} 

function destroyClickedElement(event) 
{ 
    document.body.removeChild(event.target); 
} 

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"); 
} 

</script> 

</body> 
</html> 
0

Albo to będzie działać zbyt ten sam sposób, ale bez zapisać jako wybór:

<!DOCTYPE html> 
<html> 
<head> 


<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){ 
(function() { 
var textFile = null, 
    makeTextFile = function (text) { 
    var data = new Blob([text], {type: 'text/plain'}); 

    // If we are replacing a previously generated file we need to 
    // manually revoke the object URL to avoid memory leaks. 
    if (textFile !== null) { 
     window.URL.revokeObjectURL(textFile); 
    } 

    textFile = window.URL.createObjectURL(data); 

    return textFile; 
    }; 


    var create = document.getElementById('create'), 
    textbox = document.getElementById('textbox'); 

    create.addEventListener('click', function() { 
    var link = document.getElementById('downloadlink'); 
    link.href = makeTextFile(textbox.value); 
    link.style.display = 'block'; 
    }, false); 
})(); 

}//]]> 

</script> 


</head> 

<body> 
    <textarea id="textbox">Type something here</textarea> <button id="create">Create file</button> <a download="info.txt" id="downloadlink" style="display: none">Download</a> 


    <script> 
    // tell the embed parent frame the height of the content 
    if (window.parent && window.parent.parent){ 
    window.parent.parent.postMessage(["resultsFrame", { 
     height: document.body.getBoundingClientRect().height, 
     slug: "qm5AG" 
    }], "*") 
    } 
</script> 

</body> 

</html> 
0

Najlepsze rozwiązanie, jeśli mnie o to pytasz. Spowoduje to zapisanie pliku z wybraną nazwą pliku i automatycznie w HTML lub w TXT za pomocą przycisków.

przykład:

<html> 
<head> 

<script language="Javascript" > 
function download(filename, text) { 
    var pom = document.createElement('a'); 
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 

encodeURIComponent(text)); 
    pom.setAttribute('download', filename); 

    pom.style.display = 'none'; 
    document.body.appendChild(pom); 

    pom.click(); 

    document.body.removeChild(pom); 
} 

function addTextHTML() 
{ 
    document.addtext.name.value = document.addtext.name.value + ".html" 
} 

function addTextTXT() 
{ 
    document.addtext.name.value = document.addtext.name.value + ".txt" 
} 
</script> 

</head> 
<body> 

<form name="addtext" onsubmit="download(this['name'].value, this['text'].value)"> 

<textarea rows="10" cols="70" name="text" placeholder="Type your text here:"></textarea> 
<br> 
<input type="text" name="name" value="" placeholder="File Name"> 
<input type="submit" onClick="addTextHTML();" value="Save As HTML"> 
<input type="submit" onClick="addTexttxt();" value="Save As TXT"> 

</form> 
</body> 
</html> 
Powiązane problemy