2017-04-27 181 views
-1

我正在尋找一種方法將數據從下面的HTML表單保存到僅使用JS的單獨的HTML文件中。使用JS將用戶輸入的數據保存到html文件

<!DOCTYPE html> 
<html> 
    <head> 
    <title>SaveAs</title> 
    </head> 
    <body> 
    <form> 
     <textarea rows="10" cols="70" name="text" placeholder="Type your text here:"></textarea> 
     <br /> 
     <input type="file" name="pic" id="pic"> 
     <br /> 
     <input type="text" name="name" value="" placeholder="File Name"> 
     <input type="submit" onclick="" value="Save As HTML"> 
    </form> 
    </body> 
</html> 

任何幫助表示讚賞。提前致謝!

+0

你想要保存在另一個html文件中究竟是什麼? –

+0

來自textarea的數據和來自第一個輸入的img文件。第二個輸入是新的文件名。 –

+0

沒有完美的解決方案,但是你看過'blobs'和'createObjectURL'嗎? – kojow7

回答

0

選中此項。

function save() { 
 
\t var content, text = document.getElementsByName("text")[0].value; 
 
\t var pic = document.getElementById("pic").value, filename = document.getElementsByName("name")[0].value; 
 
\t content = text + "<br><br>" + pic; 
 
\t 
 
\t var a = document.getElementById("a"); 
 
\t var file = new Blob([content], {type: 'text/html'}); 
 
\t a.href = URL.createObjectURL(file); 
 
\t a.download = filename + ".html"; 
 
}
<!DOCTYPE html> 
 
<html> 
 
    <head> 
 
    <title>SaveAs</title> 
 
\t <script src="test.js"></script> <!-- script included --> 
 
    </head> 
 
    <body> 
 
    <form> 
 
     <textarea rows="10" cols="70" name="text" placeholder="Type your text here:"></textarea> 
 
     <br /> 
 
     <input type="file" name="pic" id="pic"> 
 
     <br /> 
 
     <input type="text" name="name" value="" placeholder="File Name"> 
 
     <a id="a" href="" onclick="save()"><input type="button" value="Save As HTML"></a> <!-- link included, changed input type to button --> 
 
    </form> 
 
    </body> 
 
</html>

希望它幫助。

+0

它工作正常,但它不顯示圖像,而是顯示其中包含「假路徑」的路徑。我將嘗試着解決這個問題並獲得正確的文件路徑。非常感謝! –

相關問題