Blob from PDF File - javascript

I receive a PDF using Angular Http from an external API with using Content Type: application/pdf. So a simple Get Request, nothing fancy.
Now I need to convert this into a Blob object. However it doesn't seem to work.
How can I accomplish this in JavaScript?
Somehow directly saying let blobFile = new Blob(result) or let blobFile = new Blob([result]) doesn't seem to work.

You should be able to do the conversion when you do the request if the Content-type is application/pdf:
yourServiceMethod(): Promise<Blob> {
return this.httpClient.get(your-url, { responseType: 'blob' }).toPromise();
}
from there, you can use a utility like file-saver to complete the download process to the client's machine:
import * as FileSaver from 'file-saver';
onDownload(): void {
this.yourService.yourServiceMethod().then(file => {
FileSaver.saveAs(file, fileName);
});
}

Related

How to upload file in NodeJs to PocketBase

I'm working on a project where I need to upload many PDF files to a PocketBase collection.
I have all the files on my computer and I'd like to upload them using nodejs and the PocketBase JavaScript SDK. PocketBase expects me to send the file as a [file object], which is not possible in nodejs.
Ideally the code would look something like that:
const fileObject = loadFile(pathToFile);
const entry = {
nameField: "some-field",
fileField: fileObject
}
await pb.collection("my-collection").create(entry)
I didn't find any bits of code that could help creating a loadFile function.
You are supposed to send your form as multipart/form-data when uploading files to pocketbase.
Try:
const res = fetch(
"http://127.0.0.1:8090/api/collections/my-collection/records",
{
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
},
body: myFormWhichHasFiles,
}
)
Also, make sure you don't use JSON.stringify on your form when using multipart/form data.
Pro tip: if you leave out 'Content-type', it should default to multipart/form-data.

Downloading a zip file from a byte array

I have an api which sends a zip file as a byte array (not the byte arrays of the individual files, but the zipped file on the whole). When I trigger the api in postman, i get random characters (as shown below).
When I download this response (as option in postman: send to a file and download) in a zip file, I am able to unzip it and extract the actual files. My goal is to achieve the same thing in angular and typescript.
I have tried to convert the response to a blob and download it, as suggested in multiple places online, including this question. So I did something like
const blob = new Blob([response], { type: 'application/zip' });
const url = window.URL.createObjectURL(blob);
window.open(url);
But the resultant zip file I download says 'unable to open: empty archive'. I am not sure what I am missing here. I tried converting the response to arrayBuffer (using this) first before applying the steps as well, as that was suggested in another place online. But that hasn't been of use either.
Can someone please help me understand what I'm doing wrong. Thanks
I am calling the API in a js file:
function downloadAzureRT(params) {
return $http({
method: 'GET',
url: API.public('protectionSources/downloadArtFile'),
params: params || {},
}).then(function downloadAwsARTResp(resp){
return resp.data || {};
});
}
And then calling this function in a ts file.
downloadART() {
this.ajsPubSourceService.downloadAzureRT({
filePath: ART_FILE_PATH,
fileName: ART_FILE_NAME,
})
.then((response) => {
const blob = new Blob([response], { type: 'application/zip' });
const url = window.URL.createObjectURL(blob);
window.open(url);
}

File download through Angular 2

I have a backend that I set up to return a file through setting the header
Content-Disposition: attachment;filename=somefile.csv
It works directly in the browser and downloads the file immediately upon invoking the URL that points to that resource.
My goal is to have a button in an Angular 2 template. When the user clicks that button, I'd need to collect some data from the client-side (some IDs) and send it to the server to invoke that file download URL.
I'd like the user to stay on the same page and not have any new tabs open up but simply have the file start downloading (just like when the URL is invoked directly).
It will need to be done through a POST request because I can have quite a bit of data to send to identify what resource needs to be downloaded.
What does the call on the Angular 2 side look like for this? I tried a couple of things but I am obviously on the wrong path.
Any help would be appreciated!
I had a similar issue when i was trying to download a PDF file which my Node server was sending. I was making a GET request on my server with some id details.
This is what worked for me.
Function Calling my service
printBill(receiptID) {
this.BillingService.printBill(receiptID)
.subscribe(res => {
saveAs(res,"InvoiceNo"+receiptID+".pdf");
let fileURL = URL.createObjectURL(res);
window.open(fileURL);
})
}
Service
printBill(billID) {
return this.http.get('/billing/receipt/'+billID,
{ responseType: ResponseContentType.Blob })
.map((res) => {
return new Blob([res.blob()], { type: 'application/pdf' })
})
}
And dont forget to import ResponseContentType
Hope this helps you
i have implemented it like this.
i have a service requesting file download. The response return a url, which is on amazon s3. This is a zip file containing what i want to download.
the below works on all browsers.
in your controller
requestDownload() {
this.downloadservice.downloadImages(obj)
.subscribe(
response => this.download(response )
);
}
// res is an object
download(res){
var link = document.createElement("a");
link.download = "a";
link.href = res.link;
document.body.appendChild(link);
link.click();
}
downloadservice file
downloadImages(body): Observable<any>{
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post("/Camera51Server/getZippedImages", body, options)
.map((res:Response) => res.json())
.catch(this.handleError);
}
if you like i can give you a link to the repository.

python - send pdf as bytes in web services

I use to build a web service that response with application-json mime type.
But now I want to response a PDF as bytes, so I assume that I have to change mime type.
I will use routing but I could use flask-restful too.
The following code show the structure but I don't know how covert pdf to bytes and then send it.
#app.route('/pdf/myfile')
def pdf():
data = open("myfile.pdf", "rb").read()
# make a reponse with those bytes
return response
In the client side (angular.js) I will have this:
$http.get('/pdf/myfile', null, { responseType: 'arraybuffer' })
.success(function (data) {
var file = new Blob([data], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
You can use send_file or send_from_directory:
from flask import send_from_directory
#app.route('/pdf/myfile')
def pdf():
return send_from_directory('/dir/of/pdf', 'my.pdf')
By default this will send the file inline and browsers will probably render the PDF itself. If you set as_attachment=True the file will be presented as an attachment, and the browser will throw up a "save as" dialog box.
send_file gives you more control over things such as mime types and caching. The defaults should work well.

Download excel file in javascript from Rest API response content-disposition outputs [Object, Object]

I want to download a excel file from my angularJs code. Where i made a http post request to Java Rest API and returned the file with header
"Content-Disposition" : "attachment; filename=\"new_excel_file.xlsx\""
Java Code
#Post
#Path("/excel/trekResult")
#Produces("application/vnd.ms-excel")
public Response getResultsReport(#HeaderParam(Constants.ID) Long userId, #QueryParam(Constants.COMPANY_TREK_ID) Integer companyTrekId) {
String CONTENT_DESPOSITION = "Content-Disposition";
String CONTENT_ATTACHEMENT = "attachment; filename=\"new_excel_file.xlsx\"";
//Generates a excel file in local file system
File excelFile = misHelper.writeToFile(workBook, mis, userId, "trek-results");
return Response.ok().entity((Object)excelFile).
header(CONTENT_DESPOSITION, CONTENT_ATTACHEMENT).build();
}
On Javascript Side
myService.exportResult($scope.companyTrek.id).then(function(result) {
if(result !== undefined || result !== '') {
var blob = new Blob([result], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
var objectUrl = URL.createObjectURL(blob);
saveAs(blob, 'Trek-Results-'+fetchCurrentDate()+ '.xlsx');
}
}
Used FileSaver.js to save file.
The output file is [Object, Object]
Tested The locally generated file.
Here is a similar question for reference that didn't help me.
receive an excel file as response in javascript from a Rest service
I just noticed the Mime types are different on Java server vs Angular client.
This link shows the different MIME types related to spreadsheets.
Try making them consistent and seeing if that fixed it.
There was also this way without mishelper.

Categories

Resources