Danny Danny - 7 months ago 16
Javascript Question

creating new text file() with javascript but storing [objectFile] instead of text

I'm working on a project to encrypting data and sent it to the server, so I need to store the data in a file and then sent it to the server(php). the user then grab the file on the client side to decrypt it. But I'm runing into the problem of storing the data in the text file or open it.

I have no problem creating the file, but when I open the file/use FileReader(), it said: [objectFile] instead of the data.

What am I doing wrong? Here is an example below, I try to make it as simple as possible.
note: I can't read 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>

Answer

Try it, you can test see this working here:

function createdTextFile(){
    var date = new Date();
    var file = new File(["text text text text text text"], "textfile.txt", {type: "text", lastModified: date});
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {

        //Created download link
        //var uriContent = "data:application/octet-stream,"+file;
        var uriContent = reader.result;
        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);
    };


}
Comments