Is there a way to treat a local file (on the server) as if it was uploaded? Like fetch the file contents and put it in a array like it was a uploaded file?
So I could use it like
var file = someFunctionToRetrieveFile( url );
var re = /(?:\.([^.]+))?$/;
var name = file.name;
var ext = re.exec( name )[0];
var type = file.type;
? Is this possible in JavaScript?
Related
I have this code for file saving browsing, specifically image..
I'm aware that you can't set file programmatically, you have to go to folder popups in order to select file for security reason. So my problem is, I want the file to be saved in sessionStorage so that when the users reload the page, they don't need to reselect the image.
I'm doing this approach..
var fileInput = document.getElementById('file');
sessionStorage.input = JSON.stringify(fileInput);
But when I reload the page, it's not working anymore with..
formData.append(fileInput.files[0].name, sessionStorage.input);
I tried to do console.log(sessionStorage.inputFile) but it only printed '[object File]'
You can use below code to save image data in session storage
var file = element.files[0];
var reader = new FileReader()
reader.onload = function(base64) {
localStorage["file"] = base64;
}
//Store it in session storage
var img_base64 = localStorage["file"];
var base64_arr = img_base64_data.split(",");
var img_format = base64_arr[0].split(";")[1];
var img_content = base64_arr[1];
var file = new File([img_content], "<file name>", {type: img_format});
// get file as file.files[0] and store it in session storage
I'm extracting some data from an InDesign INDD file using a script. I'd like to save my data in a txt or json file, but my file is not saving successfully.
var data = 'string of data';
var filename = 'CS111.json';
var file = new File(filename);
var path = file.saveDlg(); //returns a valid path, but with spaces as '%20'
file.changePath(path);
var write = file.write(data); //returns false
file.close();
What am I missing here? The file doesn't show up in the chosen folder.
There are at least four steps in saving a file using InDesign Javascript: get a path and filename, create a file object, open the file, write to the file, and close the file.
I find that the write step will sometimes fail if I don't set the encoding.
//Define path and file name
var path = '~/Documents/';
var filename = 'filename.txt';
//Create File object
var file = new File(path + filename);
file.encoding = 'UTF-8';
file.open('w');
file.write('data here');
file.close();
Documentation: File class, .open(), .write()
I'm trying to write a Json object (JsonExport) and I'd like to write its content into a text file.
I'm using max4live to export data from Audio DAW to Json in order to export to a server, but after that I would like to see the whole Json Object in a text file:
var txtFile = "test.txt";
var file = new File(txtFile);
var str = JSON.stringify(JsonExport);
file.open("write"); // open file with write access
file.write(str);
file.close();
The compiler runs with no error, but i can not get the text file. I have used as well path to some of my directories and nothing.
Any idea what's happening? Thanks
I know this question already has accepted answer but I think my answer could help someone. So, the problem is to export Json data to a text file. Once you execute the following code, file will be downloaded by the browser.
const filename = 'data.json';
const jsonStr = JSON.stringify(JsonExport);
let element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(jsonStr));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
If you have access to an already existing file, just link to it. You can specify what the downloaded file name will be like this:
<a href="path/to/file.txt" download="example.json">
Download as JSON
</a>
If needed, you could also write out the dataURI as well
//Get the file contents
var txtFile = "test.txt";
var file = new File(txtFile);
var str = JSON.stringify(JsonExport);
//Save the file contents as a DataURI
var dataUri = 'data:application/json;charset=utf-8,'+ encodeURIComponent(str);
//Write it as the href for the link
var link = document.getElementById('link').href = dataUri;
Then just give the link an ID and a default href
<a href="#" id="link" download="example.json">
Download as JSON
</a>
Finally I got it! It worked by changing few parameters like this:
var txtFile = "/tmp/test.txt";
var file = new File(txtFile,"write");
var str = JSON.stringify(JsonExport);
log("opening file...");
file.open();
log("writing file..");
file.writeline(str);
file.close();
Path to my directories not allowed, so i had to save it on /tmp directory.
Thanks to all!
I am trying to save image canvas to disk as .png in chrome extension with file name reflecting MD5 hash. For this I use something like this:
var img = document.createElement("img");
img.src=canvas.toDataURL("image/png");
var image_data = atob(img.src.split(',')[1]);
var arraybuffer = new ArrayBuffer(image_data.length);
var view = new Uint8Array(arraybuffer);
for (var i=0; i<image_data.length; i++) {
view[i] = image_data.charCodeAt(i);
}
var blob = new Blob([view], {type: 'image/png'});
var url = (window.webkitURL || window.URL).createObjectURL(blob);
var b = new FileReader;
b.readAsDataURL(blob);
b.onloadend = function () {
filename = SparkMD5.hash(b.result);
}
// ....some code
chrome.downloads.download ({ url, filename+'.png', saveAs: false });
The file is saved correctly, but MD5 hash that I get in code via SparkMD5 is different from the one I see in Windows after the file is saved. I cannot understand why. Experimented a bit with different approaches to saving (directly XMLHttpRequest, etc), but no luck yet. Probably I misunderstand some basic concept, as far as I am a bit of newbee to web programming.
I have also saved files via chrome.pageCapture.saveAsMHTML with the use of FileReader and in that case MD5 are equal.
What is wrong and is there a way to get equal MD5 for filename and final file while saving .png from Chrome extension?
I have a comma separated variable in my .js file, for example:
var out='';
out+="1,val1,val2,val3,val4\n";
out+="2,val1,val2,val3,val4\n";
out+="3,val1,val2,val3,val4\n";
I am displaying this value in a browser using document.write(out);.
I would like the out variable to be downloadable as a .csv file.
From data stored in a variable, is there any way to create a csv file and its associated download link in JavaScript?
jsFiddle
Depends on browser support, but that's getting pretty good with new browsers: http://jsfiddle.net/3fMeL/2/
var CSV = [
'"1","val1","val2","val3","val4"',
'"2","val1","val2","val3","val4"',
'"3","val1","val2","val3","val4"'
].join('\n');
window.URL = window.webkitURL || window.URL;
var contentType = 'text/csv';
var csvFile = new Blob([CSV], {type: contentType});
var a = document.createElement('a');
a.download = 'my.csv';
a.href = window.URL.createObjectURL(csvFile);
a.textContent = 'Download CSV';
a.dataset.downloadurl = [contentType, a.download, a.href].join(':');
document.body.appendChild(a);
So the first item is the Blob object, this creates the object that can be downloaded. https://developer.mozilla.org/en-US/docs/Web/API/Blob (http://caniuse.com/#search=blob)
The next part is the download attribute of the link, which informs the browser to download the CSV file rather than opening it in the browser window. (http://caniuse.com/#feat=download)
there is jquery plugin for output file at the client side without server side interaction,
https://github.com/dcneiner/Downloadify