I have a function that uploads an image via a URL.
I want to change the name of the file, to download a file : 'image.jpg'.
Here's what I did:
public downloadImageJpeg(instanceUID: string, format: string): string {
var a = document.createElement("a");
a.download = 'image.jpg';
a.href = this.getRootUrl() + `/dicom/instances/${instanceUID}/wado/jpg`;
var e = document.createEvent("MouseEvents");
e.initMouseEvent("click", true, false, document.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
}
My image is uploaded but its name does not change, it is 'jpg.jpg'. Do you know why it's not 'image.jpg' ??
//////////////EDIT//////////////:
However, I think my error comes from a.href. On some examples, I saw that he was given parameters.
I tried this:
a.href = "data:image/jpg;base64," + this.getRootUrl() + `/dicom/instances/${instanceUID}/wado/jpg`;
The file name changes well but the im not downloaded, this puts me 'network failure-error'
The following function works fine:
export function download(url: string, filename: string) {
var a = document.createElement('a');
if (a.click) {
// Use a.click() if available. Otherwise, Chrome might show
// "Unsafe JavaScript attempt to initiate a navigation change
// for frame with URL" and not open the PDF at all.
// Supported by (not mentioned = untested):
// - Firefox 6 - 19 (4- does not support a.click, 5 ignores a.click)
// - Chrome 19 - 26 (18- does not support a.click)
// - Opera 9 - 12.15
// - Internet Explorer 6 - 10
// - Safari 6 (5.1- does not support a.click)
a.href = url;
a.target = '_parent';
// Use a.download if available. This increases the likelihood that
// the file is downloaded instead of opened by another PDF plugin.
if ('download' in a) {
a.download = filename;
}
// <a> must be in the document for IE and recent Firefox versions.
// (otherwise .click() is ignored)
(document.body || document.documentElement).appendChild(a);
a.click();
a.parentNode!.removeChild(a);
} else {
if (window.top === window &&
url.split('#')[0] === window.location.href.split('#')[0]) {
// If _parent == self, then opening an identical URL with different
// location hash will only cause a navigation, not a download.
var padCharacter = url.indexOf('?') === -1 ? '?' : '&';
url = url.replace(/#|$/, padCharacter + '$&');
}
window.open(url, '_parent');
}
}
Source
From PDF viewer : https://github.com/mozilla/pdf.js/blob/94089960c04d7f59eb637d6dc63944115bbc539d/web/download_manager.js#L29-L63
Related
I have the following code:
let self = this;
this.chunks = [];
const canvas2 = document.getElementById("self-canvas");
let recordStream = canvas2.captureStream(1);
var options;
options = {mimeType: 'video/webm; codecs=vp9'};
this.recorder = new MediaRecorder(recordStream, options);
this.recorder.ondataavailable = function(evt) {
self.chunks.push(evt.data);
};
this.recorder.onstop = function(evt) {
console.log("recorder stopping");
const link = document.createElement('a');
const videoBlob = new Blob(self.chunks, { type: "video/webm" });
console.log("file size: " + videoBlob.size);
const url = URL.createObjectURL(videoBlob);
link.href = url;
link.download = "sample.webm";
document.body.append(link);
link.click(); //if I comment out here I can see the video
};
console.log("finished setting controller")
console.log("recorder starting");
this.recorder.start(10000);
// the recorder.stop is called somewhere else
What it is supposed to do is pretty simple:
I have the element with id "self-canvas" that is showing my camera.
Now I am trying to record the camera and download the video from the browser using MediaRecorder, but for some reason I am unable to download the file.
I am sure that the file is being recorded, and console.log("file size: " + videoBlob.size); does not return empty.
But when I let the code run, instead of downloading the file, it tries to open it on the same window, and I cannot even see the video because the previous window disappears with the data of the recording.
However if I comment out the link.click(); I am able to see the video by opening the link on a new page (without closing the previous one). But it still doesn't download...
I used this as example, what am I doing wrong?
For heaven's sake...
I just added target blank and it worked.
link.href = url;
link.download = "sample.webm";
link.target = '_blank';
Probably because the resources are lost if it tries to open on the same page, and because it doesn't actually download the file if it is not a link "click".
Still, I never saw anyone having to add target blank in their examples like this one.
So I wonder why this is the case only for me...
I used the code suggested from Download CSV from an iPython Notebook to dynamically build the javascript code and pass it to the browser using Javascript() in python when called from a jupyter notebook. Code works great. If I embed the same code in a python function and call the python function from the same jupyter notebook, the call Javascript() in python no longer works. How can I make the reusable function work?
I am trying this on Chrome Version 73.0.3683.103 (Official Build) (64-bit) running on Windows 10. Apologies if already answered. I have scoured SO and google.
This works..
from IPython.display import Javascript
js_download = """
var csv = '%s';
var filename = 'results.csv';
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
""" % data_in_dataframes.to_csv(index=False).replace('\r','\\r').replace('\n','\\n').replace("'","\'")
Javascript(js_download)
This does not work, it fails to execute Javascript(js_download), but neither does it give any error that I can see in the jupyter notebook nor the java console in the browser. It is as if it never executed Javascript(js_download).
from IPython.display import Javascript
def js_download_csv(df_download, s_filename='results.csv'):
js_download = """
var csv = '%s';
var filename = '%s';
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
""" % (df_download.to_csv(index=False).replace('\r','\\r').replace('\n','\\n').replace("'","\'"), s_filename)
Javascript(js_download)
return None
js_download_csv(df_download, s_filename)
Apologies if I have left anything obvious out. I can find no errors or logs with any information regarding what is happening.
Any suggestions welcome.
I have found a partial answer, in that while I do not why this problem occurs, I have found how to overcome it. In https://medium.com/#tomgrek/reactive-python-javascript-communication-in-jupyter-notebook-e2a879e25906 we see in the article the following gotcha:
A big gotcha: something somewhere needs to return Javascript as its output, otherwise it doesn’t get executed in the notebook.
So, if we change the code to the following (i.e. return the Javascript call), it works.
from IPython.display import Javascript
def js_download_csv(df_download, s_filename='results.csv'):
js_download = """
var csv = '%s';
var filename = '%s';
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
""" % (df_download.to_csv(index=False).replace('\r','\\r').replace('\n','\\n').replace("'","\'"), s_filename)
return Javascript(js_download)
js_download_csv(df_download, s_filename)
I have a code in angular js which downloads an excel file on clicking a button. In chrome the file download starts automatically on clicking the button. But on Microsoft Edge clicking the button displays a prompt asking the user, whether they want to open or save file. Clicking on save button in prompt shows yet another prompt with 3 buttons OPEN, OPEN FOLDER and VIEW DOWNLOADS.
I know that edge provides settings options to disable the prompt on each download.
But is there any way on edge to start download but after downloading it does not show the second prompt asking what to do, using angular js or jquery?
The code for downloading file is as follows:
var fileName;
var a = document.createElement("a");
document.body.appendChild(a);
var type = headers('Content-Type');
var disposition = headers('Content-Disposition');
if (disposition) {
var match = disposition.match(/.*filename=\"?([^;\"]+)\"?.*/);
if (match[1])
fileName = match[1];
}
var blob = new Blob([data], {
type: type
}),
url = window.URL.createObjectURL(blob);
if (blob.size == 0) {
return;
}
a.href = url;
a.download = fileName;
var isIE = false || document.documentMode || /Edge/.test(navigator.userAgent); //if browser is IE and Edge
if (isIE) {
window.blur();
window.navigator.msSaveOrOpenBlob(blob, fileName);
} else {
a.style = "display: none";
a.click();
window.URL.revokeObjectURL(url);
}
I am trying to download a png file using the uri (code below). It works in Chrome, Firefox and Safari - but not (of course) in Internet Explorer. I am on Windows 7, so I am using IE11 in Edge Document Mode. The error is "The data area passed to a system call is too small." I've read in this MDN post
IE9 and later, as well as Edge, supports data URIs in CSS and JS
files, but not in HTML files, with a max size of 4GB.
My URI is only 1410 bytes (using uri.length). Any ideas why I am getting the error with data of this size and how to fix it?
The download function:
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
delete link;
}
The uri format:
"data:image/png;base64,iVBORw0KGgo ETC..."
The solution is below. I can't seem to find the link to give credit, but this solved it. Instead of converting the canvas to a uri first, I pass the canvas and either convert to a uri and download using a link or (for IE) I convert to a blob and use canavas.msToBlob() and msSaveBlob()
function downloadURI(canvas, name) {
if (navigator.msSaveBlob) { // IE10+
var blob = canvas.msToBlob();
return navigator.msSaveBlob(blob, name);
} else {
var uri = canvas.toDataURL("image/png")
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
if (link.click) {
link.click();
} else {
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, true, window);
link.dispatchEvent(event);
}
document.body.removeChild(link);
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Using HTML5/Javascript to generate and save a file
I want a client side HTML/JS solution to solve this problem - I have a user-edittable textarea A, a textfield B and a button C. When user clicks on C, she gets a file download with name equal to B.value and contents equal to A.value. I looked at this but it does not specify how to set the filename and I don't want a Flash solution like this. We can assume users are on latest Chrome browser (it's a little tool for my team)
Because "we can assume users are on latest Chrome browser", this type of thing can be done by creating an <a> with attributes download and href, and then clicking on it.
Example code below.
var Download = {
click : function(node) {
var ev = document.createEvent("MouseEvents");
ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
return node.dispatchEvent(ev);
},
encode : function(data) {
return 'data:application/octet-stream;base64,' + btoa( data );
},
link : function(data, name){
var a = document.createElement('a');
a.download = name || self.location.pathname.slice(self.location.pathname.lastIndexOf('/')+1);
a.href = data || self.location.href;
return a;
}
};
Download.save = function(data, name){
this.click(
this.link(
this.encode( data ),
name
)
);
};
Download.save('hello world', 'my_file.txt');