Using this code, i have the pdf's name that is incorrect : A string of random letters like a uuid.
This problem seems to only be with IE 10 / Edge.
AngularJS's version 1.4.7
this.downloadPdf = function(pdfName){
console.log(pdfName);
$http.get(config.UrlApi + "/pdf/"+ pdfName.nameFile, { responseType: 'arraybuffer' });
var a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.target = '_blank';
a.download = pdfName.name;
document.body.appendChild(a);
a.click();
});
Use the Blob Interface:
function build(response)
{
var bb = new Blob([response.data], { type: "application/pdf"});
if (URL && URL.hasOwnProperty("createObjectURL") )
{
var url = URL.createObjectURL(bb);
}
else if (window.navigator.msSaveOrOpenBlob)
{
window.navigator.msSaveOrOpenBlob(bb, 'foo.pdf');
}
}
$http.get(config.UrlApi + "/pdf/"+ pdfName.nameFile, { responseType: 'arraybuffer' }).then(build);
Blob urls are subject to an origin policy. This means that they can only be used in documents that have the same site-of-origin as the document running the script that created the url. If you need to use the blob object from an <iframe> that is running in a different domain, you must use the postMessage API to send the blob data to the frame and then create the blob: url there.
References
Saving files locally using Blob and msSaveBlob
New Blob Constructor in IE10
Edge Doesn't Use download attribute to set filename for blob URI downloading
Blob Object
URL.createObjectURL
MSDN: JavaScript Version Information
Related
I want to save somes PDF created with 'survey-pdf' on my disk.
Actually, i can send the PDF but i can't save it on my disk.
My final code :
return surveyPDF.save(filename);
Someone can help me ?
Thank you
Can you try
await surveyPDF.save(filename)
?
.save seems to be an asynchronous function that downloads the PDF file.
From the docs
Call save method of surveyPDF object to download file in browser. This is asynchronous method
#2 If the first method doesn't work, you can try this
function savePdfAsString() {
const surveyPDF = new SurveyPDF.SurveyPDF(json);
surveyPDF.data = survey.data;
surveyPDF
.raw("dataurlstring")
.then(function (text) {
//var file = new Blob([text], {type: "application/pdf"});
var a = document.createElement("a");
//a.href = URL.createObjectURL(file);
a.href = text;
a.download = "surveyAsString.pdf";
//document
// .body
// .appendChild(a);
a.click();
});
}
Here you are using the .raw function to transform the PDF into a dataurlstring and then downloading that. Here's the docs for this
*Not tested
I have a piece of HTML which I converted into an image using html-to-image and now I need to upload that image file to s3.
What I get after conversion is base 64 url. I have my s3 setup on remote backend where I send files to the api route and it uploads it to s3 and returns the s3 url for the file.
How can I convert this base url to image obj and send it to the api?
Function to convert html to img:
htmlToImage.toPng(document.getElementById('my-node'))
.then(function (dataUrl) {
// do stuff with url
});
There is a pretty simple common function which converts image data url to a file object defined as following:
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, { type:mime });
}
// Usage in your case
htmlToImage.toPng(document.getElementById('my-node'))
.then(function (dataUrl) {
const yourFile = dataURLtoFile(dataUrl, 'yourImageName');
});
The HTTP response for a POST request that I am getting from server side is a xlsx file.How do I download the file in angularjs 1?
Note: res.download() won't work here,since its a POST request that I am making,and res.download() works only for GET request
The following shall work :
$http.post("url_here", post_data_to_send, {responseType: 'arraybuffer'})
.success(function (data,status,headers) {
var blob = new Blob([data]);
var objectUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.style = "display:none";
a.href = objectUrl;
a.download = headers().filename;
a.click();
console.log("Report downloaded");
}).error(function (err) {
console.log(err);
});
You can do it directly on Client Side, you may have some cross-browser compatibility issues (the best way is always to provide a download stream via server, for large files for example).
// this example uses a JSON String
// but you can do it with any valid blob argument
const fileContent = [JSON.stringify(
['something', 'to', 'download'], null, 2
)];
const downloader = document.createElement('a');
// set the filename here
downloader.download = 'filename.json';
const blob = new Blob(fileContent, {type: 'text/plain'});
downloader.href = window.URL.createObjectURL(blob);
// trigger the download
downloader.click();
In my opinion, a redirect to the downloadable resource could be the best choice.
This question has been asked a fair bit before, but none of the solutions I've seen seem to work, potentially because of the way I stream the file back to the browser. The CSV I ultimately want is in a private S3 bucket and because of security middleware, I have to get it via a NodeJS endpoint. The code for the API is below.
exports.download = function(req, res) {
var recording = req.vsRecording,
s3 = new AWS.S3();
if(recording.data_uri){
try{
res.set('Content-Type', 'application/octet-stream');
var fileStream = s3.getObject({Bucket: 'processing-dispatched', Key: recording._id + '/aggregated.csv'}).createReadStream();
fileStream.pipe(res);
}
catch(err){
res.status(500).json({error: err});
}
}
else {
res.status(500).json({error: 'Recording does not have a report file.'});
}
};
This works perfectly and I can get the content of the file back to the browser. When it goes wrong is trying to get that content into be opened as a file download. Is there a special way to handle downloading streams?
The closest I've got is this code on the client, which sometimes seems to work on localhost if I turn my adblocker off - but does not work in production.
$scope.download = function(){
Report.download($state.params.recordingId).then(function(data){
var csvContent = "data:text/csv;charset=utf-8," + data.toString();
var encodedUri = encodeURI(csvContent);
window.open(encodedUri);
});
Report.download is just an angular service wrapper around my Node endpoint, it returns a promise and resolves the content of the file in the data variable.
reason might be the browser blocking the new window.
Allow all sites to show pop-ups in browser setting.
you can try thing in different ways create a file in node with fs and return url to the Front-end
or
you can Try the following code
$scope.download = function() {
Report.download($state.params.recordingId).then(function(data) {
var csvContent = "data:text/csv;charset=utf-8," + data.toString();
var a = document.createElement('a');
a.href = "data:application/csv;charset=utf-8," + csvContent;
a.setAttribute('download', "abc.csv");
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
}
In my project i just wanted to implement upload and download features. I have done upload functionality with AngularJS and Node.js. But here the problem is to upload a file(.pdf, all image formats) into somewhere in the system. Say for example, my project is located in D drive. Though i have to upload a file into C drive or some other drive in my computer and i have done it successfully. But when i try to read the file location from Node.js and pass the path to angular, everything is ok and file is downloaded in the browser. when i try to open a downloaded file it sends back a response - fatal error/ nothing to show. I have tried with blob only when i send a filestream instead a path to Angular.
The code is as follows
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
where data is a file stream response from the server.
not my code but try this to save a BLOB:
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
var data = { x: 42, s: "hello, world", d: new Date() },
fileName = "my-download.json";
saveData(data, fileName);
Source: http://jsfiddle.net/koldev/cw7w5/
If you want to force the download of a linked file you could use the HTML5 a option download
<a download="filename_for_download" href="path/to/the/file"> Clicking o will force a download</a>
Some more information: https://developers.google.com/web/updates/2011/08/Downloading-resources-in-HTML5-a-download?hl=en
keep the (not existing) support of older browsers in mind
One Note: Your upload process ("to upload a file into C drive or some other drive in my computer") sounds like it may be improved or rethought.