How to convert the byte code to zip file in javascript - javascript

Im using the following code to convert the byte code to zip file but it does not download the actual xml and asc file send in the response , instead it just donwloads the standard zip contents , im not aware where i am going wrong , can anyone help me with this,
$http({
url:url,
method: requestType,
data:requestBody?requestBody:"",
headers: {
'Content-type': "application/json",
"SessionID":$rootScope.token
},
responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
let blob = new Blob([data], {type: "application/zip"});
let objectUrl = URL.createObjectURL(blob);
let link = document.createElement('a');
link.href = objectUrl;
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
$scope.exp = {}; // to reset the export form after submit.
$scope.surveyReportdownloading = false;
$scope.tabActive = false;
}).error(function (error) {
//upload failed
console.log(error);
});
this is not downloading the actual files at all. Can anyone help me through this. The byte cod ethat backend team is sending is as follows.
"PK:8xJMÆVÞ|xl/workbook.xml ¢( ÍnÂ0ïúÖ>#MpR­¸{C,²vdѾ}CR¢¶'n;³³fË«u磵göI­ñ«  ¡+8÷²AþÅvhú]mÐKwⶮµÄBxEwØ ­ñî<´GX¾s(oµ#6°|~b¬¼5;h¼úAöƽîÍd|ñ¿©rMbFVð~!îØ`nT10Wè~Ø4SäiÅÑ,ÇWøÁÿC|¼í¶ëÃzûL/ó4KËYZG0U:üþÂòPK:8xJnmt?Ø[Content_Types].xml ¢( ÅMNÃ0¯y·] vl¡\À²'ÕøGIiÏÆ#q& TUЪº²lÏ{ßõä·÷é|ãl
mð¥#×ÁX¿,EKU~#æ³éË6f\ê±5Q¼u
Na"x¾©Brx2*½RKÑèZêà <åÔyÙôÕ6=løxÀ²\dwC]±±Z_˵7¿ y¨*«ÁÝ:(5¹¦è×Â)ë¯zc¹ Áã _S¬ìk°¶w'~Äd
dèQ9öF¾´êBÙ/ãâ¼ÃîüÿkiÛ>þfå"Ç㿽Sç =ÉÞ']d£áºE
îdþ`s(}Oâ&K\­gJü=x?½wÈþ}PK
38xJ£ ²×rels/.rels ¢( ï»¿PK:8xJILE#¥¶xl/worksheets/sheet1.xml ¢( ¥ÛrÇEÅ÷èn\U\¡\q®ª%^ÿþõ˯ûÃ/·W»Ýñìÿ|"
Any help is appreciated. Thanks!

Seems like the issue is with the type parameter try with the below code
You can access the content-type from headers.
If it doesn't work, try with application/zip, application/octet-stream
$http({
url: url,
method: requestType,
data: requestBody ? requestBody : "",
headers: {
'Content-type': "application/json",
"SessionID": $rootScope.token
},
responseType: 'arraybuffer'
}).success(function(data, status, headers, config) {
let blob = new Blob([data], {
type: headers['content-type']
// OR
// type:"application/zip, application/octet-stream"
});
let objectUrl = URL.createObjectURL(blob);
let link = document.createElement('a');
link.href = objectUrl;
link.download = fileName;
link.click();
window.URL.revokeObjectURL(link.href);
$scope.exp = {}; // to reset the export form after submit.
$scope.surveyReportdownloading = false;
$scope.tabActive = false;
}).error(function(error) {
//upload failed
console.log(error);
});
var blob = new Blob([response.data],{type:headers['content-type']});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "Filename";
link.click();

Related

View or download PDF from Api Rest fetch

I am trying to finish a download of a PDF from an API Rest. I can't see the pdf completely in a new browser tab, I get a chorme pop up with the message "Error
An error occurred while loading the PDF document."
I have the following:
function download_2() {
var myHeaders = new Headers();
myHeaders.append(
"Authorization",
"mytokennnnnnnnnnnnn"
);
var requestOptions = {
method: "GET",
headers: myHeaders,
redirect: "follow",
};
fetch(
"myAPIRESTurlurlurlurlurl",
requestOptions
)
.then((response) => response.text())
.then((result) => {
let blob = new Blob([result.data], { type: "application/pdf" });
var arrayBuff;
var fileReader = new FileReader();
fileReader.onload = function (event) {
arrayBuff = event.target.result;
};
fileReader.readAsArrayBuffer(blob);
var URL = window.URL || window.webkitURL;
const url = window.URL.createObjectURL(blob);
const link = document.createElement("a");
link.target = "_blank";
link.href = url;
//I apend the link element
document.body.appendChild(link);
//download
link.click();
// Clean and remove the link
link.parentNode.removeChild(link);
URL.revokeObjectURL(url);
})
.catch((error) => console.log("error", error));
}
I've also used the fileReader to then pass the blob to it, but I'm not sure if I'm doing it right.
Thank you for the help.
Regards.
Did you try to add the download="true" attribute to the href tag you created ?

Download a PNG file served as binary/octet-stream

steps that will reproduce the problem :
I am saving a Blob object as form data using a service and I am receiving the response as content-type: application/octet-stream as in attached image
What is the expected result?
To download and view the the application/octet-stream as a image into local machine and view it using applications
What happens instead?
able to download the file as image but it says we dont support this file format though its (ex:image.png)
function add() {
$.ajax({
url: 'https://localhost:3000/upload/sampleImage.png',
type: 'GET',
success: function (data) {
const link = document.createElement('a');
link.style.display = 'none';
link.download = "sample image";
link.href =
'data:' +
'image/png' +
';base64,' +
window.btoa(unescape(encodeURIComponent(data)));
link.click();
},
error: function (request, error) {
alert("Request: " + JSON.stringify(request));
}
});
}
Any ways to download the file and preview it successfully
Set the responseType as blob in request
Using HttpClient:
this.http.get("https://localhost:3000/upload/sampleImage.png",{responseType:'blob'}).subscribe((img)=>{
const link = document.createElement('a');
link.style.display = 'none';
link.download = "sample image";
link.href =window.URL.createObjectURL(data);
link.click();
});
Now using $.ajax(not recommended,avoid using it) specify the dataType as blob and use window.URL.createObjectURL(data) to create URL
$.ajax({
url: 'https://localhost:3000/upload/sampleImage.png',
type: 'GET',
xhrFields:{
responseType: 'blob'
},
success: function (data) {
const link = document.createElement('a');
link.style.display = 'none';
link.download = "sample image";
var blob = new Blob([data], {type: 'image/png'});
link.href =window.URL.createObjectURL(blob);
link.click();
},
error: function (request, error) {
alert("Request: " + JSON.stringify(request));
}

Excel file corrupted on download with axios vuejs

I am trying to download an excel file. I have used axios for it.
I have tried the below code
axios.post(backendURL + 'api/client?file_name='+file_name,params, {
file_name: file_name
}, {
responseType: 'blob'
}).then((response) => {
const url = URL.createObjectURL(new Blob([response.data], {
type: 'application/vnd.ms-excel'
}))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', file_name)
document.body.appendChild(link)
link.click()
});
I am getting the error as "Excel cannot open the file "filename.xlsx" because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file"
I have tried all the solutions which I found in google but nothing worked. Please help
downloadFile() {
axios({
url: this.scenario.file, //.substring(0, this.scenario.file.lastIndexOf("/"))
method: "GET",
headers: {"Accept": "application/vnd.ms-excel"},
responseType: "blob"
}).then(response => {
const fileURL = window.URL.createObjectURL(new Blob([response.data]));
const fileLink = document.createElement("a");
fileLink.href = fileURL;
fileLink.setAttribute("download", "file.xlsx");
document.body.appendChild(fileLink);
fileLink.click();
});
},

How can I create file from application/octet-stream data?

I have a REST API that returns application/octet-stream as MediaType and now I need to create a file and download it in client side!
$("#export-space-excel-button").click(function(e) {
e.preventDefault();
$("#export-excel-space-dialog").hide();
$("#export-excel-space-progress-dialog").css("display","");
$("#export-excel-space-progress-dialog").show();
$.ajax({
url : AJS.contextPath() + "/export/excel/space/"+spaceKey,
type : "GET",
data : {data1:data1},
responseType: 'application/octet-stream',
contentType: 'application/json',
success: function(data) {
const url = window.URL.createObjectURL(new Blob([data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'test.xlsx');
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
$("#export-excel-space-progress-dialog").hide();
}
});
});

Loading a Blob (PDF) with Angularjs into iFrame Filename?

Hello currently I'm loading a blob via angularjs into a iframe, however when saving the blob it has some wierd filenames is there a way to specify it?
Here is my code:
let id = $routeParams.id;
$http({
url: `http://..../${id}/`,
method: 'GET',
data: {},
headers: {
'Content-Type': 'application/json'
},
responseType: 'arraybuffer'
}).success((data, status, headers, config) => {
var blob = new Blob([data], {type: 'application/pdf'});
var url = window.URL || window.webkitURL;
var objectUrl = url.createObjectURL(blob);
this.blob = $sce.trustAsResourceUrl(objectUrl);
});

Categories