Download image only by its URL

3

I have this requisition:

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

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

});

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

I tried this, but it did not work, he just opened a flap and showed the image.

window.location.href=(exportUrl+d1);
    
asked by anonymous 07.11.2017 / 19:11

1 answer

1

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

Understand that the code below runs a function through the click, but you can rotate the function inside your response :

  •   
        

    Execulate the code below right here and click on 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>
    
07.11.2017 / 19:50