How can I Customize URL Created using createObjectURL, - javascript

I have the following code to create a pdf document and i would like to open it without showing download window, I used a.download so that currently its displaying download dialog to avoid that i tried it without a.download but the url looks like blob:https://localhost/6767676-d5d5f-4150-85bf-456333bebd17 but How can i customize to display as https://localhost/productNumber.pdf instead
$.ajax({
url: '/product/product/CreateSOEntryLine',
type: 'POST',
data: data,
success: function (data) {
var request = new XMLHttpRequest();
var formData = new URLSearchParams();
formData.set("productID", data.productID);
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
var a = document.createElement('a');
var fileURL = window.URL.createObjectURL(request.response);
a.href = fileURL;
a.download = `${data.productNumber}.pdf`;// without this line automatically open in a new tab thats what i want but i need to customize url as https://localhost/productNumber.pdf
a.style.display = 'none';
a.setAttribute('target', '_blank');
document.body.appendChild(a);
a.click();
}
};
var url = `#(Url.Action("createPDF", "product", new { Area = "product" }))?` + formData.toString();
request.open("GET", url);
request.setRequestHeader("Content-Type", "application/json");
request.responseType = 'blob';
request.send();
}
})
currently the url looks like blob:https://localhost/6767676-d5d5f-4150-85bf-45787898ebd17 but i would like to see https://localhost/productNumber.pdf

Related

Ajax file download over GET not working in Opera

This code works in all major browsers excpet in latest Opera 71 (Windows).
The behaviour is that no error or info shows up but the download never starts from end user perspective. In developer tools I see the binary content of the example pdf document in response tab.
It seems that the dynamic creation of tags is not working.
function downloadFile(urlToSend) {
var req = new XMLHttpRequest();
req.open("GET", urlToSend, true);
req.responseType = "blob";
req.onload = function (event) {
var URL = window.URL || window.webkitURL;
var contentType = req.getResponseHeader('content-type');
var blob = new Blob([req.response], {type: contentType});
var downloadUrl = URL.createObjectURL(blob);
var contentDisposition = req.getResponseHeader('content-disposition');
//var fileName = req.getResponseHeader("fileName") //if you have the fileName header available
var filename = 'doku.pdf'; //contentDisposition.match(/filename*="(.+)"/)[1];
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location.href = downloadUrl;
} else {
//code which gets executed by Opera
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location.href = downloadUrl;
}
};
req.send();
}

Download of jQuery Ajax request contents is empty

I have a PHP file that returns output in PDF - Works fine if I access the file directly.
I'd like to retrieve the PDF file through AJAX.
In native Javascript, it works fine:
var req = new XMLHttpRequest();
req.open("POST", "./api/pdftest.php?wpid="+wpid, true);
req.responseType = "blob";
req.onreadystatechange = function ()
{
if (req.readyState === 4 && req.status === 200)
{
var blob=req.response;
var filename = "test.pdf";
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "test.pdf";
link.click();
var file = new File([blob], filename, { type: 'application/force-download' });
window.open(URL.createObjectURL(file));
}
};
req.send();
But I guess I'd use jQuery to ensure cross browser compatibility (although the snippet above works in Edge, Chrome and Firefox on pc, I haven't tested it in other browsers/on other platforms)
So I tried to rewrite the function:
url='./api/pdftest.php?wpid='+wpid;
$.ajax(
{
url: url,
method: 'POST',
responseType: 'blob',
success: function(data)
{
var filename='test.pdf';
var blob=new Blob([data]);
var filename = "test.pdf";
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "test.pdf";
link.click();
var file = new File([blob], filename, { type: 'application/force-download' });
window.open(URL.createObjectURL(file));
}
});
The jQuery equivalent allows me to download a PDF file but … the PDF file is empty.
So I guess I am doing something wrong, probably in the DATA to BLOB conversion. But what? I hope somebody can see what I am doing wrong.
I've been using ages on StackOverflow, read many suggestions - but didn't find any answer. I simply can't see the forest for the trees.
Looking at the documentation for the jQuery.ajax() function, we see there's no setting called responseType, so you need to use xhrFields to directly set a property of the XHR object. And, since you're only setting the URL and success callback, we can just use the shorter jquery.post() function.
So the data is returned, we make a Blob and then a URL to download it. I'm not on Windows so I can't test if that link I constructed will work as expected, but figured I'd do it the jQuery way.
var url = './api/pdftest.php?wpid=' + wpid;
$.post({
url: url,
xhrFields: {responseType: "blob"},
success: function(data) {
// don't set the MIME type to pdf or it will display
var blob = new Blob([data], {type: "application/octet-stream"});
// build a blob URL
var bloburl = window.URL.createObjectURL(blob);
// trigger download for edge
var link = $("<a>").attr({href: bloburl, download: "test.pdf"}).click();
// trigger download for other browsers
window.open(bloburl);
}
});
Probably double!
This is the solution I found thanks to Hisham at Download pdf file using jquery ajax:
First, add the following plugin that can be used to the XHR V2 capabilities missing in JQuery: https://github.com/acigna/jquery-ajax-native
Then:
url='./api/pdftest.php?wpid='+wpid;
$.ajax(
{
dataType: 'native',
url: url,
xhrFields:
{
responseType: 'blob'
},
success: function(blob)
{
var filename = "test.pdf";
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "test.pdf";
link.click();
var file = new File([blob], filename, { type: 'application/force-download' });
window.open(URL.createObjectURL(file));
}
});
This seems to be working.
Note: the window.open() is to make download possible in Firefox, the link.click() method Works in Edge, Chrome and Opera
Thanks to miken32 for pointing into the right direction.
As binary data is not possible to retrieve through jQuery.ajax, Native is the only way, at least for now. The following method works in Edge, Firefox, Chrome and Opera - tested on WIndows 10.
var req = new XMLHttpRequest();
req.open("POST", "./api/pdftest.php?wpid="+wpid, true);
req.responseType = "blob";
req.onreadystatechange = function ()
{
if (req.readyState === 4 && req.status === 200)
{
var blob=req.response;
var filename = "test.pdf";
var link = document.createElement('a');
link.setAttribute("type", "hidden"); // make it hidden if needed
link.href = window.URL.createObjectURL(blob);
link.download = "test.pdf";
document.body.appendChild(link);
link.click();
link.remove();
var file = new File([blob], filename, { type: 'application/force-download' });
//window.open(URL.createObjectURL(file));
}
};
req.send();

Zip download is not happening

Hi I am new to java script, I am trying to download zip file from a web server running in http://10.1.2.137:5000/download.
When I access the URL alone in the browser as http://10.1.2.137:5000/download, te zip file is getting downloaded , but when I call from java script , the zip file is getting corrupted it seems. Not able to open the zip file with win rar.
Not sure this is the issue with CORS.
$scope.downloadData = function (){
console.log ('Entering in to Download Method')
var url = 'http://10.1.2.137:5000/download';
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.responseType = "arraybuffer";
var linkElement = document.createElement('iframe');
document.body.appendChild(linkElement)
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var blob = new Blob([str2bytes(xhr.response)], {type: "application/zip"});
var fileName = "logs.zip";
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, filename);
} else {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display:none";
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}
}
}
};
You can use window.open, this will instruct the browser to open the url and start download. e.g.
window.open("http://10.1.2.137:5000/download","_self");

Open FileStreamResult by ajax (as downloaded file)

Is it possible to use an ajax call to open FileStreamResult as a downloaded file?
Controller method
public FileStreamResult DownloadPDF()
{
var stream = myHandler.getFileStream("myfile.pdf");
return File(stream, "application/pdf", "myfile.pdf"));
}
Html code
Click Me
<script type="text/javascript>
$("a.mydownload").click(function () {
$.ajax({
method: 'GET',
url: 'http://myserver/file/DownloadPDF',
success: function (data, status, jqXHR) {
var blob = new Blob([data], { type: "application/pdf" })
var url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.click();
}
});
});
</script>
Running on IE I get access denied, but on Chrome it runs fine. I do however get a "blank"/invalid pdf.
Use XMLHttpRequest() with responseType set to "blob", add download attribute to <a> element
$("a.mydownload").click(function () {
var request = new XMLHttpRequest();
request.responseType = "blob";
request.open("GET", "http://myserver/file/DownloadPDF");
request.onload = function() {
var url = window.URL.createObjectURL(this.response);
var a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = this.response.name || "download-" + $.now()
a.click();
}
request.send();
});
alternatively, you can use jquery-ajax-blob-arraybuffer.js. See also Add support for HTML5 XHR v2 with responseType set to 'arraybuffer' on $.ajax
Still had issues with IE11, but a minor change to #guest271314 solutions, seems to do the trick.
Set responseType after open.
Use msSaveBlob on IE
$("a.mydownload").click(function() {
var request = new XMLHttpRequest();
request.open("GET", "http://myserver/file/DownloadPDF");
request.responseType = "blob";
request.onload = function() {
var msie = window.navigator.userAgent.indexOf("MSIE");
if (msie > 0) {
window.navigator.msSaveBlob(this.response, "myfile.pdf");
} else {
var url = window.URL.createObjectURL(this.response);
var a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = this.response.name || "download-" + $.now()
a.click();
}
}
request.send();
});

Downloading file from ajax result using blob

I use this code to download excel file from server.
$.ajax({
headers: CLIENT.authorize(),
url: '/server/url',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jsonData),
success: function (data) {
alert('Data size: ' + data.length);
var blob = new Blob([data], { type: "application/vnd.ms-excel" });
alert('BLOB SIZE: ' + data.length);
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
document.location = downloadUrl;
},
});
The problem I experience is that even though data and blob sizes are identical, the moment document.location gets assigned I'm prompted to download almoste two times larger excel file. And when I try to open it, excel complains about wrong file format and opened file contains a lot of garbage, even though required text is still there.
Any ideas what is causing this and how to avoid it?
So I solved the problem using AJAX 2. It natively supports binary streams. You can't use jQuery for that, unless you base64 encode everything, apparently.
Working code looks like this:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/le/url', true);
xhr.responseType = 'blob';
$.each(SERVER.authorization(), function(k, v) {
xhr.setRequestHeader(k, v);
});
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.onload = function(e) {
preloader.modal('hide');
if (this.status == 200) {
var blob = new Blob([this.response], {type: 'application/vnd.ms-excel'});
var downloadUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = downloadUrl;
a.download = "data.xls";
document.body.appendChild(a);
a.click();
} else {
alert('Unable to download excel.')
}
};
xhr.send(JSON.stringify(jsonData));
Hope this helps.

Categories