Download image only by its URL

Asked

Viewed 760 times

3

I have this requisition:

var exportUrl = 'http://export.highcharts.com/';

$.post(exportUrl, d1, function(d1) {

});

Since exportUrl+D1 becomes the url of my image generated by the server. how do I continue the process and download it ?

I tried it like this, but it didn’t work, it just opened a tab and showed the image.

window.location.href=(exportUrl+d1);

1 answer

1


With pure javascript you can download an image with only URL, but first you need to convert it to file and "play" within an html and force the download.

Understand that the code below runs a function by clicking, but you can run the function inside your sponse:


  • Run the code below right here and click Download

function download_next(files) {
    //percorre o array de arquivos
		files.forEach(function (element, i, array) {
		
    //enquanto houver interação
		if (i >= files.length) {
			return;
		}	
	  
    //cria um html <a>
		var a = document.createElement('a');
    
    //insere o arquivo no <a> criado
		a.href = files[i].download;
    
    //insere um atribute target
		a.target = '_parent';
    
    //criando download
		if ('download' in a) {
		a.download = files[i].filename;
		}
    
    //realizando click automático e baixando o arquivo após 1 segundo
		(document.body || document.documentElement).appendChild(a);
		if (a.click) {
			setTimeout(function() {
				a.click();
			}, 1000);
		} 
    
    //removendo o elemento
		a.parentNode.removeChild(a);		
	
		});
	}
<a onclick="download_next([{ download:'https://cdn.sstatic.net/Sites/br/img/[email protected]'}])" style="background: red; color: #fff; padding: 10px; cursor: pointer;">Baixar imagem</a>

  • here and on my machine is not performing that automatic click

  • It must be some javascript error, see your console, leave it open and try again and see if there are any errors. It’s downloading here?

  • Unfortunately not downloading, and also no error appears. in your is downloading?

  • Note that you have to make sure that the image url is valid and that she’s inside it: [{download: 'http://imagem.png'}] before passing the function. Can you download from here? In the example above?

  • Lolipop only by clicking the button (a)

  • Exactly! You have to generate the action, run the function... In this example you need to click the button.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.