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);
});
Related
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 ?
I am trying to open a PDF file in a new tab and want to read file without downloading it in local machine.
I tried this function, but it is not loading my pdf and giving error can not load pdf
function readFileInNewTab (fileId) {
let url = BASE_URL + "api/CMS/Documents/Download/" + fileId;
const requestOptions = {
method: 'GET',
headers: { 'Content-Type': 'application/pdf', ...authHeader(url) },
credentials: 'include',
responseType: "blob", // important
};
inProgress = true;
return fetch (url, requestOptions).then(handleResponse)
.then((response)=> {
const file = new Blob([response], { type: "application/pdf" });
//Build a URL from the file
const fileURL = URL.createObjectURL(file);
//Open the URL on new Window
debugger
const pdfWindow = window.open();
pdfWindow.location.href = fileURL;
})
.catch((error) => {
console.log(error);
});
} ```
I'm having an issue Updating a blobs name - I have done this no problem before but in this case I'm storing the blob in IndexedDB and based on certain conditions (save/saveas) it gets a name from Google Drive or you can add a new name.
Dom JS File
//Convert Text to Blob
let file = text;
fileName = "NewFileName";
let metadata = {
name: fileName, // Filename
mimeType: "application/pdf", // mimeType at Google Drive
};
let form = new FormData();
form.append(
"metadata",
new Blob([JSON.stringify(metadata)], { type: "application/json" })
);
form.append("file", file);
let textBlob = new Blob([file], {
'type': 'application/pdf',
});
Then My ServiceWorker Receives it and renames it then uploads it to google Drive
let blobPDF = request.result.text;
let blob = new Blob([blobPDF], {
type: "application/pdf"
});
let newBlob = new FormData();
console.log("Blob Name : " + saveas)
//Set New Name
newBlob.append("blob", blob, saveas);
fetch(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id",
{
method: "POST",
headers: new Headers({ Authorization: "Bearer " + accessToken }),
body: blob // Also tried newBlob var -> Got not a blob error
}
)
if I use the var newBlob it says it's not a blob and errors - then changed to "file" it still doesn't set name
One obvious mistake is that you're sending the blob itself as the body of your fetch request, not the newBlob form data object with the filename.
fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id", {
method: "POST",
headers: new Headers({ Authorization: "Bearer " + accessToken }),
body: newBlob
// ^^^^
})
If that doesn't help, I'd try creating a File instead of a Blob:
let blob = new File([blobPDF], saveas, {
type: "application/pdf"
});
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();
I provide a method on my WebApi to download a file:
public HttpResponseMessage Get(int id)
{
MemoryStream file = RetrieveFile(id);
if (file != null)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(file);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "dummy.txt"
};
return response;
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
This works fine and i can consume it with a WebClient.
I also tied to implement the javascript front-end using FileSaver.js :
$http({
url: myUrl,
method: 'GET',
params: {
id: 1
},
headers: {
'Content-type': 'application/json'
}
}).success(function (data, status, headers, config) {
var file = new Blob([data], {
type: 'application/octet-stream'
});
saveAs(file, "test.txt");
}).error(function (data, status, headers, config) {
});
This works great but it fails on IE9 since FileSaver and Blop is not supported.
I have tried opening the url in a new window but can't find a decent working solution for IE9