1
我正在開發一個項目來加密數據並將其發送到服務器,所以我需要將數據存儲在一個文件中,然後發送它到服務器(PHP)。用戶然後抓住客戶端上的文件來解密它。但我遇到了將數據存儲在文本文件中或打開它的問題。用JavaScript創建新的文本文件()但存儲[objectFile]而不是文本
我沒有創建文件的問題,但是當我打開文件/使用FileReader()時,它說:[objectFile]而不是數據。
我在做什麼錯?下面是一個例子,我儘量簡化它。 注意:我無法讀取jquery。
<!DOCTYPE html>
<html>
<head>
<script>
function createdTextFile(){
var date = new Date();
var file = new File(["text text text text text text"], "textfile.txt", {type: "text", lastModified: date});
/*
sent file to server
var formdata = new FormData();
formdata.append("Uploaded_file", file);
*/
//Created download link
var uriContent = "data:application/octet-stream,"+file;
var div_idFileDownload = document.getElementById("file_dowload");
div_idFileDownload.innerHTML = "";
var createElement_aFileDownload = document.createElement("a");
createElement_aFileDownload.setAttribute("download", "textfile.txt");
createElement_aFileDownload.setAttribute("href", uriContent);
div_idFileDownload.appendChild(createElement_aFileDownload);
var nm = document.createTextNode("textfile.txt");
createElement_aFileDownload.appendChild(nm);
}
//open text file: [objectFile]
//Need the text file to say: text text text text text text
</script>
</head>
<input type="file" id="upload_img">
<input type="button" onclick ="createdTextFile()" value="download">
<div id="file_dowload"><div/>
</html>
好,我明白了!難怪PHP閱讀它就好了。我不知道你可以使用FileReader()的結果作爲url。謝謝安德森,你爲我節省了數小時的試驗和錯誤。 (: – toastext
歡迎您,爲您的情況,MDN的例子完美地工作:https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL –