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));
}
Related
I am trying to download image using below code. But file showed as download with error
(Failed - Network error)
I am using below code
$scope.downloadDocument = function (doc) {
$http({
method: "GET",
url: appConfig.apiUrl + "/downloadDoc/" + $scope.array.nic + "/" + doc.fileName
}).then(function (response) {
console.log(response);
$scope.downloadedImage = response.data;
var a = document.createElement("a"); //Create <a>
a.href = "data:image/jpge;base64," + response.data; //Image Base64 Goes here
console.log(a);
a.download = doc.fileName; //File name Here
a.click(); //Downloaded file
}, function (response) {
$log.log(response);
});
}
My response
When I click download button. It shows as download with error. Check below image
How i do this correctly. please help
You need to add responseType:'blob' your request,
also I prefer use object url (https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL) for downloading files
function downloadBlob(blob, name) {
const data = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = data;
link.target = '_self';
link.download = name;
link.dispatchEvent(
new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window
})
);
setTimeout(() => {
window.URL.revokeObjectURL(data);
link.remove();
}, 100);
}
$scope.downloadDocument = function (doc) {
$http({
method: "GET",
url: appConfig.apiUrl + "/downloadDoc/" + $scope.array.nic + "/" + doc.fileName,
responseType: 'blob'
}).then(function (response) {
console.log(response);
downloadBlob(new Blob([response.data]), doc.fileName);
}, function (response) {
$log.log(response);
});
}
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();
});
},
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:
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();
}
});
});
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();