React - the downloaded pdf is blank - javascript

At first, I send a GET request for the pdf data
const config = {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
baseURL: 'https://my-site.com',
};
const axiosInstance = axios.create({config});
const pdf = await axiosInstance.get('url', {
headers: { Authorization: 'Bearer ' + accessToken, Accept: '*/*' },
})
The value of pdf is the same as below
Then I tried to download the file
const url = window.URL.createObjectURL(new Blob([pdf]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `FileName.pdf`);
// Append to html link element page
document.body.appendChild(link);
// Start download
link.click();
I can download the pdf file successfully, but the pdf is blank when I open it.
How to fix it?

Fix it by adding responseType: 'blob'
const pdf = await axiosInstance.get('url', {
headers: { Authorization: 'Bearer ' + accessToken, Accept: '*/*' },
responseType: 'blob',
})

Related

React native image upload getting network error

'react-native-image-picker' for uploading image in my application, Sometimes it is uploading and sometimes i am getting [TypeError: Network request failed] below is the code:
FormData in my component:
//image is :file:///data/user/0/com.testApp/cache/rn_image_picker_lib_temp_0d38d959-6ece-4750-a215-4b3f68002f4e.jpg
let formData = new FormData();
formData.append('images', { uri:image, name: imageSelected?.fileName, type: 'image/png' });
const response = await updateUserProfile(userDetails,formData)
Service call:
export const updateUserProfile = async (userDetails,data) => {
const response = await fetch(`${baseUrl}/updateusersprofile/${userDetails._id}`, {
method: "PATCH",
headers: {
//"Content-Type": "application/json",
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${userDetails.token}`,
},
body: data,
});
return await response;
};
In Postman i have checked the api is working fine, What would be the problem in my code.
export const updateUserProfile = async (userDetails,data) => {
const response = await fetch(`${baseUrl}/updateusersprofile/${userDetails._id}`, {
method: "PATCH",
headers: {
//"Content-Type": "application/json",
'Content-Type': 'multipart/form-data',
Authorization: `Bearer ${userDetails.token}`,
},
body: JSON.stringify(data),
});
return await response;
};

How to open PDF in a new tab from Cloud without downloading it in local machine

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

How to download a ReadableStream on the browser that has been returned from fetch

I am receiving a ReadableStream from a server, returned from my fetch call.
A ReadableStream is returned but I don't know how to trigger a download from this stage. I can't use the url in an href because it requires an Authorization token.
I don't want to install fs on the client so what options do I have?
try {
const res = await fetch(url, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/octet-stream'
}
});
const blob = await res.blob();
const newBlob = new Blob([blob]);
const newUrl = window.URL.createObjectURL(newBlob);
const link = document.createElement('a');
link.href = newUrl;
link.setAttribute('download', 'filename');
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
window.URL.revokeObjectURL(newBlob);
} catch (error) {
console.log(error);
}
Update 1
I converted the file to a Blob, then passed it into a newly generated href. Successfully downloaded a file. The end result was the ReadStream contents as a .txt file.
Meaning stuff like this
x:ÚêÒÓ%¶âÜTb∞\܃
I have found 2 solutions, both worked but I was missing a simple addition to make them work.
The native solution is
try {
const res = await fetch(url, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`
}
});
const blob = await res.blob();
const newBlob = new Blob([blob]);
const blobUrl = window.URL.createObjectURL(newBlob);
const link = document.createElement('a');
link.href = blobUrl;
link.setAttribute('download', `${filename}.${extension}`);
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
// clean up Url
window.URL.revokeObjectURL(blobUrl);
This version is using the npm package steamSaver for anyone who would prefer it.
try {
const res = await fetch(url, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`
}
});
const fileStream = streamSaver.createWriteStream(`${filename}.${extension}`);
const writer = fileStream.getWriter();
const reader = res.body.getReader();
const pump = () => reader.read()
.then(({ value, done }) => {
if (done) writer.close();
else {
writer.write(value);
return writer.ready.then(pump);
}
});
await pump()
.then(() => console.log('Closed the stream, Done writing'))
.catch(err => console.log(err));
The key for why it was not working was because I did not include the extension, so it either errored out because of the mimetype was wrong or it opens a .txt file with a string of the body instead of the image.

Download PDF file forcefully instead of opening new tab using javascript

Here's what i've done so far. I managed to download the file but it's giving me "object%200%object" on the url when i try to open the file.
fetch({
url,
method: 'GET',
responseType: 'blob', // important
contentDisposition: 'attachment',
contentType: 'application/pdf',
mode: 'no-cors'
})
.then(r => r.blob())
.then((response) => {
console.log(response);
const s = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.setAttribute('download', `test.pdf`);
link.click();
});

Uploading File to specific folder in Google drive in Angular 4

I am trying to upload a file to a specific folder, but I am unable to do it.
Uploading is working correctly but it is not putting a file in a particular folder.
I am trying to do a Resumable upload with google drive rest version 3.
Assuming I already have a Folder ID.
First getting uploading URI :
uploadFileToDrive(name: string, content: string): Promise<Object> {
const url = `https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable`;
const accessToken = localStorage.getItem('accessToken');
let headers = new Headers({
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer ' + accessToken,
});
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http
.post(url, { name: name, role: 'reader', type: 'anyone', 'parents': [{"id":parentId}] }, options)
.toPromise()
.then(response => this.gDriveUploadFile(content, response.headers.get('location')));
}
Second uploading media :
gDriveUploadFile(file, url): Promise<any> { //file and url we got from first func
console.log(file + " "+ url );
const accessToken = localStorage.getItem('accessToken');
let headers = new Headers({
'Authorization': 'Bearer ' + accessToken,
'Content-Type': 'application/json; charset=UTF-8',
'X-Upload-Content-Type': file.type ,
});
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http.post(`${url}`, file, options) //call proper resumable upload endpoint and pass just file as body
.toPromise()
}
Also, I would like to know how I will be able to create a folder using google rest API in angular.

Categories