Pass image as a binary representation - javascript

I'm invoking an api that accepts image in the binary representation form. I'm uploading the image through a file upload html.
Here is my code:
let fileReader = new FileReader();
let fileData = fileReader.readAsArrayBuffer(text.data.uploadedFile);
yield call(fetchJson, 'url/fetch', {
method: 'POST',
headers: {
Authentication: 'Basic <key>',
'Content-type': 'image/jpeg'
},
body: fileData
});
I get fileData as undefined and my request does not go through. This 3rd party API accepts image in binary representation form in the body.
This is equivalent to the following in POSTMAN:
This works in POSTMAN but not sure how to achieve this using code.
I set uploadedFile on front-end using: event.target.files[0]

Related

How to send a POST request as form-data when FormData is unavailable? (Airtable scripts)

The Cloudinary API requires to send data using multipart/form-data, but I'm working in an environment where FormData is not available.
How could I do something as simple as this, then?
const formData = new FormData();
formData.append('file', assetUrl);
formData.append('upload_preset', CLOUDINARY_UNSIGNED_UPLOAD_PRESET);
formData.append('cloud_name', CLOUDINARY_CLOUD_NAME);
console.debug(`Uploading file (id: ${id}) to Cloudinary`, CLOUDINARY_UPLOAD_URL, formData);
const response = await fetch(CLOUDINARY_UPLOAD_URL, {
method: 'POST',
body: formData,
});
I tried different approaches, but it seems the Cloudinary API is really sensitive about it, and doesn't allow sending data in any other format other than multipart/form-data.
Cloudinary API supports not only multipart/form-data, but also JSON and application/x-www-form-urlencoded.
If you're sending a string as the value of the file parameter, such as a remote URL (in your case) or Base64, then you can use any of the above-mentioned Content-Types.
For example, you could try the following example which will successfully upload the image into a cloud (you'll want to replace <your-cloud>, <file-url> and <upload-preset> with your actual values):
fetch('https://api.cloudinary.com/v1_1/<your-cloud>/image/upload', {
method: 'POST',
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
'file': '<file-url>',
'upload_preset': '<upload-preset>'
})
});
Note that the cloud_name is derived from the URL you're sending the data to therefore it should not be sent in your request body.

Download Excel works in Postman but doesn't in Javascript

I'm trying to download an Excel file via AJAX (using Axios). I'm doing this way because I need to send a JWT token to access to it.
Now, I'm getting a file response with the content like this:
Which seems to be binary. In Postman I can set the token and click Save and download button and all works. Now, this is my code in JS:
requestWithFullResponse({
url: url,
method: 'GET',
}, this.props.token, false).then((response) => {
const responseData = response.data
// I've tried with different types and nothing works
// var blob = new Blob([responseData], { type: `${response.headers['content-type']};charset=utf-8` });
// var blob = new Blob([responseData], { type: 'application/octet-stream;charset=utf-8' });
var blob = new Blob([responseData], { type: 'application/octet-stream' });
saveAs(blob, filename, true)
}).catch((error) => { console.log('Error downloading file -> ', error); });
That code downloads the file, but when I open It it Libre Office says that the file is corrupt. What I'm missing? Is there a way to see the code executed by Postman when downloads the file?
Any kind of help would be really appreciated
You need to set: responseType: 'blob'. The default is application/json.

PDF Blob is showing nothing in new tab, using stream from backend

I used https://github.com/barryvdh/laravel-dompdf
stream method for sending a response to front-end.
Here is my code which I wrote for opening pdf in a new tab.I'm calling stream from backend API in result it gives a response but when I try to create blob it shows nothing in PDF.
APICaller({
method: 'get',
responseType: "arraybuffer",
headers: {
'Accept': 'application/pdf'
},
endpoint: gep('generate/certificate?path=certificate.pdf', 'v3'),
}).then( (data) => {
var file = new Blob([data.data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
here is Empty PDF
I had a similar issue with axios, it doesn't work for downloading files using Blob. Use XMLHttpRequest and do the similar response handler in its on('load') event to achieve file download.

Generating PDF from wkhtml using PHP wrapper, when sent back to Angular 4, opens only in Chrome

I generate a html in Angular 4, send it to PHP wrapper for wkhtmltopdf, after that it is returned to Angular, and this works fine in Chrome, the PDF is displayed. I need it to be displayed also in Firefox. This is the code that sends the PDF to PHP:
public getPdf() {
const html = this.pdfEl.innerHTML;
alert(html);
this.rest.post(
'/pdf',
{ html },
{
headers: new Headers(),
responseType: ResponseContentType.Blob
}
).subscribe(
(value) => {
//alert('subscribe receiver in pdf button directive');
this.url = URL.createObjectURL(value.blob());
open(this.url);
});
}
Things that I have tried so far, but none worked are:
1. Setting this.url = URL.createObjectURL(new Blob([value.blob()], {type: 'application/pdf'})); instead of this.url = URL.createObjectURL(value.blob());
2. Setting this as headers instead of new Headers() :
new Headers({
'Content-Type': 'application/json',
'Accept': 'application/pdf'
}),
any suggestions to resolve this, guys? Thanks.
If value.blob() returns a Blob you have also set the blob type to application/pdf. That has to be done on the response side, because the property is read only.
Blob Documentation
Blob.type Read only A string indicating the MIME type of the data
contained in the Blob. If the type is unknown, this string is empty.
Or if you value.blob() returns only an array buffer you have to create a new Blob on your own.
new Blob([value.blob()], {type: 'application/pdf'});

Posting a base64 encoded PDF file with AJAX

I'm trying to post a base64-encoded PDF file to a Zendesk file upload API endpoint but the file URL returned from the API shows that the file is corrupted.
First I receive the PDF as a base64-encoded string from a separate API call. Let's call it base64String.
If I do window.open("data:application/pdf;base64," + base64String) I can view the PDF in my browser.
Now I am trying to follow the documentation here for uploading files via the API. I can successfully complete a cURL call as shown in the example. However, the jQuery AJAX call will corrupt the PDF file.
client.request({
url: '/api/v2/uploads.json?filename=test.pdf',
type: 'POST',
data: atob(base64String),
contentType: 'application/binary'
}).then(function(data) {
window.open(data.upload.attachment.content_url); // corrupt file
}, function(response) {
console.log("Failed to upload file to Zendesk.");
console.log(response);
});
Like I said, this will succeed but when I visit the content_url the PDF does not display. I am quite sure the file is being corrupt in the POST request.
I have tried uploading the file as a base64 string (without decoding with atob()) with no luck among other things.
UPDATE
I'm still not able to view the PDF after converting the base64 string to blob.
var blob = base64ToBlob(base64String);
console.log(blob); // Blob {size:39574, type: "application/pdf"}
client.request({
url: '/api/v2/uploads.json?filename=test.pdf',
type: 'POST',
data: blob,
processData: false,
contentType: 'application/pdf'
}).then(function(data) {
window.open(data.upload.attachment.content_url); // corrupt file
}, function(response) {
console.log("Failed to upload file to Zendesk.");
console.log(response);
});
function base64ToBlob(byteString) {
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
var blob = new Blob([ab], {type: 'application/pdf'});
return blob;
};
I learned that the Zendesk app framework uses a jQuery AJAX wrapper for requests and the arraybuffer type is unsupported, so the file was getting corrupted. The app framework team has fixed the issue.

Categories