Make file available for download via Avascript

Asked

Viewed 11,683 times

4

I have a javascript application where the user can view certain files from the server. I would like to know how to make these files available for download, something like a "Save As" button. Thank you in advance.

  • Just make a window.location.href='caminhoDoArquivoParaDownload'; doesn’t solve?

  • Managed to resolve this?

2 answers

1

Hello, this will do?

The attribute download downloads the file in href.

function mudarLink() {
  var baixar = document.getElementById('baixar');
  baixar.href = "http://cdn.sstatic.net/img/share-sprite-new.svg?v=24e64812c790";
  baixar.innerHTML = "Baixar imagem Stack Exchange";
}
<button onclick="mudarLink()">Mude o Link</button>
<a id="baixar" href="http://cdn.sstatic.net/br/img/sprites.svg?v=e26b234630f5" download>Baixar imagem Stack Overflow</a>

Edited:

Note that does not work in all browsers: http://caniuse.com/#feat=download

  • This serves in parts, need the argument for href to be dynamic, ie variable according to the file the user chooses. I’m using a Cobol program, but the download part needs to be done in javascript.

  • You can change the href with javascript. Maybe: document.getElementById("id").href = "link";. See the edited response for in example how to use.

  • solved @Ricardoribeiro

0

my problem was: download after selecting a solved option like this:

<select id="tipo_documento" name="tipo_documento">
<option value="" disabled="disabled" selected="selected">.:: Modelos de Documentos ::.</option>
<option value="Documentos/DayCamp/Contrato.doc">Contrato.doc</option>
<option value="Documentos/DayCamp/Orçamento.doc">Orçamento.doc</option>
</select>

<a href="#" download id="btnBaixarModelo" name="btnBaixarModelo" class="btn bg-purple form-control pull-right"  title="Baixar Modelo">
<i class="fa fa-cloud-download mao" title="Baixar Modelo"></i>
</a>

$('#frmOrcamento #tipo_documento').on('change',function(){
var url = $(this).val();$('#frmOrcamento #btnBaixarModelo').attr({'href':url});
})

I know that "download" does not work on some browsers, but my client uses Chrome and firefox. Business rule: when selecting an option it copies and pastes the path to the link from the[ class . btn => bootstrap ]

Try to create something similar, it is possible that this idea of mine helps you, success!

Browser other questions tagged

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