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

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();
}
});
});

Related

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 download Excel file in Vue.js application correctly?

I'm struggling to download an Excel file in xlsx format in my Vue.js application. My Vue.js application make post request to the Node.js application which download that Excel file from remote SFTP server. Backend application works without any problems.
In Vue.js application I use next code:
axios.post(config.backendHost + '/excel', {
file_name: fileName
}).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', fileName)
document.body.appendChild(link)
link.click()
});
After downloading file by browser, file opens automatically and I am experiencing an error that looks like this:
We found a problem with some content .xlsx. Do you want us to try and recover as much as we can?
You need to add the response type as a third argument in your post call
{
responseType: 'blob'
}
Your final code like that
axios.post(config.backendHost + '/excel', {
file_name: fileName
}, {
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', fileName)
document.body.appendChild(link)
link.click()
});
Or you can use the library FileSaver.js to save your file
import FileSaver from 'file-saver'
axios.post(config.backendHost + '/excel', {
file_name: fileName
}, {
responseType: 'blob'
}).then((response) => {
// response.data is a blob type
FileSaver.saveAs(response.data, fileName);
});
my case worked:
axios.get(`/api/v1/companies/${companyId}/export`, {
responseType: 'blob',
}).then((response) => {
const url = URL.createObjectURL(new Blob([response.data]))
const link = document.createElement('a')
link.href = url
link.setAttribute(
'download',
`${companyId}-${new Date().toLocaleDateString()}.xlsx`
)
document.body.appendChild(link)
link.click()
})

Download excel cannot open the file because the file format or file extension

const data = ('start_date=2019-07-04&end_date=2019-07-24');
axios({
url: `http://localhost:4000/report/data?${data}`,
method: 'GET',
responseType: "arraybuffer", // important
}).then(response => {
// BLOB NAVIGATOR
let blob = new Blob([response.data], { type: '' });
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob);
} else {
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.setAttribute('download', '');
document.body.appendChild(link);
link.download = [];
link.click();
document.body.removeChild(link);
}
});
I'm trying to download an xlsx file with reactJS but i'm receiving this message when i try to open my file after download:
"Excel can not open file 'file.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 file format"
Here's the frontend code:

How to convert the byte code to zip file in 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();

Categories