New File stucks - javascript

I am new in javascript and was trying to read and write in local txt file so I did as I found in the web but for some reason it stucks in new File instantiation:
<script type="text/javascript">
var txtFile = "d:/test.txt"
alert('point 1');
var file = new File(txtFile);
alert('point 2');
</script>
It prints only 'point 1' string. Thanks.

new File() constructor requires at least two parameters; first parameter an array containing String, ArrayBufferView, ArrayBuffer Blob or another File object; the second the file name. You cannot specify a download directory for files using javascript, but you can set a download directory at browser settings or preferences. You can also utilize download attribute at a element to set file name at Save File dialog.
I am new in javascript and was trying to read and write in local txt
file
You could use <input type="file"> element to retrieve test.txt, and edit .txt file at <textarea> before re-saving with same file name. See also Edit, save, self-modifying HTML document; format generated HTML, JavaScript , How to Write in file (user directory) using JavaScript?
<script type="text/javascript">
var txtFile = "test.txt";
var text = "abc";
var file = new File([text], txtFile);
console.log(file);
var a = document.createElement("a");
a.download = file.name;
a.href = URL.createObjectURL(file);
document.body.appendChild(a);
a.innerHTML = file.name;
a.onclick = function() {
this.parentElement.removeChild(this)
}
</script>

Related

Angular - Save blob in local text file?

I have a plain text variable which I want to store and save on a .txt file using Angular.
So far I have tried the following:
var data = new Blob([text], {type: 'text/plain'});
const url= window.URL.createObjectURL(data);
window.open(url);
Being text the variable with the plain text content. It seems to work but it opens de blob on a new browser tab, and I need it to be downloaded as whatever.txt.
How can I achieve this? Thanks!
The solution can be found here:
JavaScript blob filename without link
The steps are the following:
Create a hidden <a> tag.
Set its href attribute to the blob's URL.
Set its download attribute to the filename.
Click on the <a> tag.
This is working code from my application
const file = new window.Blob([data], { type: contentType });
const downloadAncher = document.createElement("a");
downloadAncher.style.display = "none";
const fileURL = URL.createObjectURL(file);
downloadAncher.href = fileURL;
downloadAncher.download = fileName;
downloadAncher.click();

Save a JSON file to server with javascript application

I'm developing a simple Javascript application where the user has some images (stored in my machine) and he is able to annotate them and then save the annotations as a JSON file.
The application is very light and simple and it is not an app server.
However, I need to save those JSON files to the machine that will be behaving as the server.
Since I cannot use Javascript for IO, is there any easy and simple way to save those files without having to implement an app server?
I used Blob to download the files.
function project_save_confirmed(input) {
if ( input.project_name.value !== _onco_settings.project.name ) {
project_set_name(input.project_name.value);
}
// onco project
var _onco_project = { '_onco_settings': _onco_settings,
'_onco_img_metadata': _onco_img_metadata,
'_onco_attributes': _onco_attributes };
var filename = input.project_name.value + '.json';
var data_blob = new Blob( [JSON.stringify(_onco_project)],
{type: 'text/json;charset=utf-8'});
save_data_to_local_file(data_blob, filename);
user_input_default_cancel_handler();
}
function save_data_to_local_file(data, filename) {
var a = document.createElement('a');
a.href = URL.createObjectURL(data);
a.download = filename;
a.click();
}
Any suggestion?
Kind regards!
Copy paste from: Download JSON object as a file from browser
function downloadObjectAsJson(exportObj, exportName){
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataStr);
downloadAnchorNode.setAttribute("download", exportName + ".json");
document.body.appendChild(downloadAnchorNode); // required for firefox
downloadAnchorNode.click();
downloadAnchorNode.remove();
}
This I believe accomplishes what you want, just makes sure that the proper headers are set, push it to an <a> tag, then click() it
You can do this in php:
<?php
//notice this will put WHATEVER is in json into file
$filename="config.json";
if (isset($_POST["json"])) {
file_put_contents($filename,$_POST["json"]);
}
?>
then for the JS side:
var fd=new FormData();
fd.append("json", JSON.stringify(_onco_project));
fetch("https://url.com",{method:"POST",body:fd})
Explanation: JS makes a new formdata, and sets "json" to the stringified json, and sends it off to the server. The php server takes this, and puts it directly into $filename. Make sure data is safe before putting it to file, as it will take whatever it is given and put it into your file!

Is it possible to create an xml from json in the browser, then download that xml?

I'm about to create a client side app, which at the end should create and xml file and offer to the user to download it to the computer.
Is it possible to create and download xml from the browser?
Yes, it's possible.
function downloadXMLFromJSON(jsonString) {
let fileName = 'sample.xml';
let xmlStr = new X2JS().json2xml_str(JSON.parse(jsonString));
let a = document.createElement('a');
a.download = fileName;
a.href = URL.createObjectURL(new File([xmlStr], fileName, {type: 'text/xml'}));
a.click();
}
downloadXMLFromJSON(`{"x": "a", "y": "b"}`);
<script src="https://rawgit.com/abdmob/x2js/master/xml2json.min.js"></script>
You're going to need an external library for converting JSON to XML (x2js in this case). Then you can use an in memory a tag with download attribute to download xml file.

How to read the first line of .txt file?

can anyone one help how to read the first line of .txt file? I have input type file that upload example.txt then I would like to grab the first line from that code. I tried something like this:
<input type="file" id="fileUpload" name="fileUpload"/> MyTest.txt //file name
function confirmFileSubmit(){
var fileName = $('#fileUpload').val();
alert($('#fileUpload').split('\n')[0]);
}
After I run my code this just outputted file name in alert box. I'm not sure how I can read the content of the file. If anyone can help please let me know.
You'll need the FileReader for that
function confirmFileSubmit(){
var input = document.getElementById('fileUpload'); // get the input
var file = input.files[0]; // assuming single file, no multiple
var reader = new FileReader();
reader.onload = function(e) {
var text = reader.result; // the entire file
var firstLine = text.split('\n').shift(); // first line
console.log(firstLine); // use the console for debugging
}
reader.readAsText(file, 'UTF-8'); // or whatever encoding you're using
// UTF-8 is default, so this argument
} // is not really needed

Javascript Blob document with html tags to be saved with formatting

I am having some text like below to be saved in a downloadable doc format using javascript blob.
<p style='font-size:18px'>Hello</p>
Once the download happens I want the doc to show just show formatted 'Hello' without any html tags. In ubuntu this works very well.
But when I open the same doc in windows or google docs, I still see html tags.
Is there a way where I can do this formatting at Blob level itself. Below is the way Iam creating blob object.
var file = new Blob([val], {type: "octet/stream"});
Appreciate your help on this.
Try adjusting type of Blob to "text/html" , using URL.objectCreateURL() as file object reference for download
var val = "<div>abc</div>";
var file = new Blob([val], {
type: "text/html"
});
// file object reference
var download = URL.createObjectURL(file);
var a = document.createElement("a");
a.href = download;
a.download = "file-" + new Date().getTime();
document.body.appendChild(a);
a.click()

Categories