Last active
April 6, 2021 12:13
-
-
Save kauanmocelin/2382b4133b93446b0494ea4e62d36dd4 to your computer and use it in GitHub Desktop.
[Download de Arquivo via xmlhttprequest] #ajax #xmlhttprequest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var form = document.getElementById('frm_upload'); | |
var formData = new FormData(form); | |
************************************************** Com arrayBuffer *************************************************************** | |
var xhr = new XMLHttpRequest(); | |
xhr.open('POST', 'exibirProtocoloDigital.do?action=exibirVolumePDF&arquivo='+codArquivo+'&codigoOrgaoPara='+codigoOrgaoPara, true); | |
xhr.responseType = 'arraybuffer'; | |
xhr.send(formData); | |
xhr.onload = function(e) { | |
if (this.status == 200) { | |
var blob=new Blob([this.response], {type:"application/pdf"}); | |
var pdfurl = window.URL.createObjectURL(blob); | |
window.open(pdfurl); | |
} | |
}; | |
xhr.send(formData); | |
OUTRA FORMA DE FAZER - arrayBuffer | |
var xhr=new XMLHTTPRequest(); | |
xhr.open("GET", url, true); | |
//Now set response type | |
xhr.responseType = 'arraybuffer'; | |
xhr.addEventListener('load',function(){ | |
if (xhr.status === 200){ | |
console.log(xhr.response) // ArrayBuffer | |
console.log(new Blob([xhr.response])) // Blob | |
} | |
}) | |
xhr.send(); | |
************************************************** Com blob direto *************************************************************** | |
var xhr = new XMLHttpRequest(); | |
xhr.open('POST', 'URL', true); | |
xhr.responseType = 'blob'; | |
xhr.send(formData); | |
xhr.onload = function(e) { | |
if (this.status == 200) { | |
var blob = this.response; | |
var pdfurl = window.URL.createObjectURL(blob); | |
window.open(pdfurl); | |
} else { | |
console.log(xhr.responseText); | |
} | |
}; | |
xhr.send(formData); | |
************************************************** responseType dinamico - trata erro************************************************** | |
var xhr = new XMLHttpRequest(); | |
xhr.open('POST', 'exibirProtocoloDigital.do?action=exibirVolumePDF&numeroProtocolo='+numeroProtocolo+'&codigoOrgaoPara='+codigoOrgaoPara, true); | |
xhr.onreadystatechange = function() { | |
if (xhr.readyState == 2) { | |
if (xhr.status == 200) { | |
xhr.responseType = 'blob'; | |
} else { | |
xhr.responseType = 'text/html'; | |
} | |
} else if (xhr.readyState == 4) { | |
if (xhr.status == 200) { | |
var blob = this.response; | |
var pdfurl = window.URL.createObjectURL(blob); | |
window.open(pdfurl); | |
} else { | |
exibirMsg(xhr.responseText, "erro") | |
} | |
} | |
}; | |
xhr.send(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment