Parse text/csv from server and download it - javascript

How to download file with data which comes from server in text/csv format?
I'm using fetch. I have function like this
download(content, filename, contentType)
{
const a = document.createElement('a');
a.href = 'data:text/csv;charset=utf-8,' + encodeURI(content);
a.target = '_blank';
a.download = filename;
a.click();
}
Response comes like object.
Hope your help!

bruteforce method: replace the filename extension with .csv and then send it to your client. You can achieve that with php.
replace filename extension with php
good solution : if you want to convert a file to csv, you will need a rather powerful api. Maybe your best bet is to read the file yourself if you know what youre expecting, and generate the CSV.

Related

Converting Object into JSON and downloading as a .json file in React

I have a javascript object that contains some information.
I want to convert this into JSON and download it as a .json file.
Seems like I can just to JSON.stringify(obj) to convert it into JSON
but how do I actually download it as a .json file?
I'm not sure this is a React-specific issue if you're just looking to download data via JavaScript, but here's a snippet I use that creates a link to download the data content, virtually clicking the element, and finally removing it from the DOM. It should support both modern browsers and older IEs:
private exportToJson(objectData: SomeObject) {
let filename = "export.json";
let contentType = "application/json;charset=utf-8;";
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([decodeURIComponent(encodeURI(JSON.stringify(objectData)))], { type: contentType });
navigator.msSaveOrOpenBlob(blob, filename);
} else {
var a = document.createElement('a');
a.download = filename;
a.href = 'data:' + contentType + ',' + encodeURIComponent(JSON.stringify(objectData));
a.target = '_blank';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
}
It's also worth noting that there are a number of ways to approach this as cited in this SO question.
For those arriving here and searching for an easier solution:
<a
href={`data:text/json;charset=utf-8,${encodeURIComponent(
JSON.stringify(YOURJSON)
)}`}
download="filename.json"
>
{`Download Json`}
</a>
You won't be able to create a file directly on your computer's file system as this would be a huge security risk. You cannot do this from a web page using JavaScript.
You could write a server side service to post your state to and it creates a file - you may then download the file or be content with where your server side stores it.
Another way via inMemory Create a file in memory for user to download, not through server

Download/Save file in react js

How can i save the response from api which gives me excel file with data and name ?
I have below api which gives me the excel file and i have to save it at default location as is.
https://mydomain.dev.com/export
I have gone through the multiple articles on the web but everywhere its explained to save the data as excel file at client side which is not the my case. For me, file type and name is already decided at server side and i have to just save as is.
Thanks a lot in advance
Here's how I usually handle this:
I start out by fetching the file and then use downloadjs to download the blob
async downloadFile() {
const res = await fetch("https://mydomain.dev.com/export");
const blob = res.blob();
// from downloadjs it will download your file
download(blob, "file.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
I always use this script to do this:
function downloadFile(absoluteUrl) {
var link = document.createElement('a');
link.href = absoluteUrl;
link.download = 'true';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
};
So just :
downloadFile("https://mydomain.dev.com/export");
It is working, but i hope that there is better solution.

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.

Download large file >1GB using http protocol, java and javascript

I have a web application for downloading files. Everything works fine except when I want to download a file more than 1GB .
This is my java code:
InputStream in = new FileInputStream(new File(folderFile.getAbsolutePath()));
org.apache.commons.io.IOUtils.copy(in, response.getOutputStream());
response.flushBuffer();
in.close();
HTTP request :
$http({
method:'get',
url:this.apiDownloadFileUrl,
responseType:'arraybuffer',
cache: false
});
and here is client side: I got data successfully on client, but when I make it Blob , if the data size was more than 500MB , nothing happened and it wasn't downloaded. Also, I can download 300MB ...
How can I check if it is a memory problem, or a server problem? ... When I download from gmail , I can download more than 1GB .
.success(function(databack) {
var file = new Blob([ databack ], {
type : 'application/csv'
});
var fileURL = window.URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = data;
document.body.appendChild(a);
a.click();
Have you tried using the copyLarge() methods from IOUtils? For the copy() methods the JavaDoc says:
"For large streams use the copyLarge(InputStream, OutputStream) method."
You should check the response message first, and decide which side fire the problem.
As my experience, you should check whether the file was cached by the browser rather than any problems~

Javascript:write a string with multiple lines to a csv file for downloading

I am trying to write a string that has multiple lines (comes from the server side) into a csv file for user to download in browser. However, using my code, I only get the csv files with all the data in a single line.
Here is my code:
function getReport(){
var report = "a,b,c,d;1,2,3,4;";
//console.log(report);
var csvcontent="";
while (report.indexOf(";")!=-1)
{
csvcontent=csvcontent+ report.substring(0,report.indexOf(";"))+"\n";
report=report.substring(report.indexOf(";")+1);
}
console.log(csvcontent);
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + csvcontent;
a.target = '_blank';
a.download = 'myFile.csv';
document.body.appendChild(a);
//console.log("ok");
a.click();
}
In the downloaded csv file, all the data will in a single line a,b,c,d1,2,3,4.
Can anyone tell me how to solve this problem?
Thanks in advance!
Try this instead
a.href = 'data:text/csv;charset=utf-8;base64,' + window.btoa(csvcontent);
It converts the data to base64 which properly encodes the new line character. Why it doesn't work in your method I'm really not sure. One caveat is the btoa function won't work in older browsers check out this question for more information How can you encode a string to Base64 in JavaScript?

Categories