Create json/text file to folder in local machine using javascript - javascript

I need to create a text or json file and save file to user selected location in local machine using Javascript. I used below code but it downloads the file to Downloads directory
download(text:any, name:any, type:any) {
var a = document.createElement("a");
var file = new Blob([text], {type: type});
a.href = URL.createObjectURL(file);
a.download = name;
a.click();
}
Below is what I am looking
My application has a diagram and the diagram data can be exported as json data
User want to save this data to a file in selected location. Lets say C:\Temp, This will help in sharing the diagram data with other users and they can import it into their application
We want to implement notepad File -> SaveAs kind of functionality here

Related

Download File to Specific Directory JS

I'm taking inputs from an HTML form and putting them into a file. I've currently got it so it automatically downloads the file to the downloads folder but I want it to download to a specific directory:
%AppData%/Code/User/snippets/
Here is the code I've got at the moment:
function createSnippet() {
var snipName = document.getElementById('snipName').value;
var snipScope = document.getElementById('snipScope').value;
var snipPrefix = document.getElementById('snipPrefix').value;
var snipBody = document.getElementById('snipBody').value;
var snipDesc = document.getElementById('snipDesc').value;
// Final
let CONTENT = (`
{
"${snipName}": {
"scope": "${snipScope}",
"prefix": "${snipPrefix}",
"body": [
"${snipBody}"
],
"description": "${snipDesc}"
}
}
`);
var a = document.createElement("a");
a.href = window.URL.createObjectURL(new Blob([CONTENT], {type: "text/plain"}));
a.download = `${snipName}.code-snippets`; // I want this to download to the directory shown above
a.click();
}
Using JS, this cannot be done. If your trying to download a file to specific destination in the drive it is not possible. This possess a huge security risk if browsers allow it.
When a user is viewing a website, they are using a browser to access the webpage and browser decides what all permissions a website can have and what limitations it should put.
The only way that you download a file in specific folder is,the user doing to himself. Otherwise downloads made by browser will be stored at some default destination like /user/Downloads or user chosen path /user/Downloads/Chrome_Downloads.

MIME Type for excel file from Blazor Server side project

I am trying to download a List of Items as excel from Blazor server side project . I used CsvHelper to generate the byte[] from the list and using the below code to download the byte[] content as excel file .
The code from Blazor Component is like below [ Click event of button to download excel]
#inject IJSRuntime JsRuntime
private async Task ExportToExcel()
{
jobStarted = true;
var fileBytes= ExportHelper.ConvertContactDataToCsv(); // This will return byte[] of contacts
if (await JsRuntime.InvokeAsync<bool>("confirm", $"Do you want to Export?"))
{
var fileName = $"Contacts";
await JsRuntime.InvokeAsync<object>("saveAsFile", fileName, Convert.ToBase64String(fileBytes));
}
jobStarted = false;
}
The Javascript code is like below
window.saveAsFile = function (fileName, byteBase64) {
var link = this.document.createElement('a');
link.download = fileName;
link.href = "data:application/vnd.ms-excel;base64," + byteBase64;
this.document.body.appendChild(link);
link.click();
this.document.body.removeChild(link);
}
Execution of this generates the file without any issues , but while opening the file using Microsoft Excel the warning message is like
The file format and extension of 'Contacts.xls' don't match. The file
could be corrupted or unsafe. Unless you trust its source, don't open
it. Do you want to open it anyway?
And if i ignore the warning and proceed with opening all contents in excel looks good
Now i tried to generate file with extension xlsx and different mime type inside JS code The changes are like
var fileName = $"Contacts.xlsx";
and inside JS tried these 2 combinations separately
link.href = "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," + byteBase64;
link.href = "data:application/octet-stream;base64," + byteBase64;
The code executed without any issues and files getting generated but while opening file the warning is like
Excel cannot open the file 'Contacts.xlsx' because the file format
for the file extension is not valid.’ Verify that the file has not
been corrupted and that the file extension matches the format of the
file
I am not able to open the file at all.
So what is the right MIME type to be used to ensure downloaded excel file can be opened in Excel without warnings
Since you are using CsvHelper (via ConvertContactDataToCsv) your output file is a Comma Separated Value text file, not a binary Excel .xls file.
Don't use the .xls file extension, instead use e.g. .csv;
so Contacts.csv instead of Contacts.xls.
For the mime type, you might use text/csv.
But foremost, it is the wrong file extension that makes Excel error on that file.

Any way to download stored text in session storage as file attachment to browser?

I store some data in sessionStorage/localStorage. Is there any way to download that data as file attachment directly to the browser?
Get that data from the storage and use File api to create new file in the memory
let myFile = new File(data, "Filename.txt[anything]",{type:"plain/text"}]);
let url = URL.createObjectURL(myFile);
let a = document.createElement("a");
a.href(url);
a.setAttribute("download","data.txt");
a.click();

Browser only downloading certain Base64 file types

I have Base64 files that I am trying to have the user download. I do not need these or want these to display in the browser. I need these to download. The data seems to be coming back fine, but only certain types of files are behaving.
I am grabbing down the data in an ajax call and then checking to see if there is any data.
$('button').on('click', function(){
...ajax call
if (data) {
var encode = 'data:image/' + data.dataTypeCode + ';base64,'
var image = encode+data.data;
window.open(image, '_blank');
}
})
This is only opening the word, excel, gif, mpg, tif and pdf files.
This is not opening the png, jpg, mp3 files which I find odd.
You cannot force a user to automatically download a file simply due to the file represented as a data URI or Blob URL being opened in a window. You can offer a file to be downloaded.
const a = document.createElement("a");
a.download = "fileName";
a.href = /* data URI, Blob URL*/;
document.body.appendChild(a);
a.click();

save a field value to a file on desktop

I am developing a custom application in "ServiceNow" which requires Javascript and HTML coding. So, I have a field say, "description" on my form. How may I save this field's value to a word document on the desktop?
While JavaScript cannot create a file for you to download by itself, ServiceNow does have a way for you to create one. Creating a Word document is impossible without the use of a MID server and some custom Java code, but if any file type will do you can create an Excel file using an export URL. To test this out, I made a UI Action in a developer instance running Helsinki on the Problem table. I made a list view that contains only the field that I wanted to save, and then used the following code in the UI action:
function startDownload() {
window.open("https://dev13274.service-now.com/problem_list.do?EXCEL&sysparm_query=sys_id%3D" +
g_form.getUniqueValue() + "&sysparm_first_row=1&sysparm_view=download");
}
When the UI action is used, it opens a new tab that will close almost immediately and prompt the user to save or open an Excel file that contains the contents of that single field.
If you want to know more about the different ways you can export data from ServiceNow, check their wiki-page on the subject.
You can use the HTML5 FileSystem API to achieve that
window.requestFileSystem(window.PERSISTENT, 1024*1024, function (fs) {
fs.root.getFile('file.txt', {create: true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
var blob = new Blob([description.value], {type: 'text/plain'});
fileWriter.write(blob);
});
});
});
FYI, chrome supports webkitRequestFileSystem.
Alternatively, use a Blob and generate download link
var text = document.getElementById("description").value;
var blob = new Blob([text], {type:'text/plain'});
var fileName = "test.txt";
var downloadLink = document.createElement("a");
downloadLink.download = fileName;
downloadLink.href = window.webkitURL.createObjectURL(textFile);
downloadLink.click();
Javascript protects clients against malicious servers who would want to read files on their computer. For that reason, you cannot read or write a file to the client's computer with javascript UNLESS you use some kind of file upload control that implicitely asks for the user's permission.

Categories

Resources