Blank images and pdfs downloaded from Dropbox - javascript

I have a problem when downloading files from my dropbox.
While using the type 'text/csv' I can download and view txt files.
Chaning the type to 'image/jpeg' or 'application/pdf' and download the filetype gives me blank file.
Am I on the right track here or is there another way this should be done?
main.service.ts
downloadFile(id) {
const headers = new Headers();
headers.append('Authorization', 'Bearer ' + this.accessToken);
const path = `{"path": "${id}"}`;
headers.append('Dropbox-API-Arg', path);
return this.http.post('https://content.dropboxapi.com/2/files/download',
null, { headers: headers });
}
main.component.ts
downloadFileBlob(data: any, name) {
const blob = new Blob([data], { type: 'image/jpeg' });
const url = window.URL.createObjectURL(blob);
window.open(url);
}
saveFile(id, name) {
this.dropbox.downloadFile(id).subscribe((data: any) => {
this.downloadFileBlob(data._body, name); });
}

Turns out I was going at this the wrong way.
Dropbox github has an example of using sharingGetSharedLinkFile, which works about the same as filesDownload.
Replace sharingGetSharedLinkFile with filesDownload and provide a file path instead of the URL.
Something like this:
function downloadFile() {
var ACCESS_TOKEN = (<HTMLInputElement> document.getElementById('access-
token')).value;
var SHARED_LINK = (<HTMLInputElement> document.getElementById('shared-
link')).value;
var dbx = new Dropbox.Dropbox({ accessToken: ACCESS_TOKEN });
dbx.filesDownload({path: SHARED_LINK})
.then(function(data) {
var downloadUrl = URL.createObjectURL((<any> data).fileBlob);
var downloadButton = document.createElement('a');
downloadButton.setAttribute('href', downloadUrl);
downloadButton.setAttribute('download', data.name);
downloadButton.setAttribute('class', 'button');
downloadButton.innerText = 'Download: ' + data.name;
document.getElementById('results').appendChild(downloadButton);
});
}

Related

Download excel file created in node using SheetJS/XLXS [NodeJS] [React]

I'm trying to generate a xlsx file using SheetJS in node. Then in my frontend I have a button to call this route and download the file. Currently I have the following:
// backend code
export function exportExcel(req: Request, res: Response) {
try {
const workbook = utils.book_new();
const fileName = "sample";
const dataSheet = utils.json_to_sheet(sampleData);
utils.book_append_sheet(workbook, dataSheet, fileName.replace("/", ""));
const binaryWorkbook = write(workbook, {
type: "array",
bookType: "xlsx",
});
return res.status(OK).send(binaryWorkbook);
} catch (_error) {
return res.sendStatus(500)
}
}
Then in the front end I have the following:
const handleExcelExport = () => {
const { data } = await axios.get(
`/export-excel`,
{
responseType: "blob",
}
).then(response => {
const blob = new Blob([response], {
type: "application/octet-stream",
});
const link = document.createElement("a");
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
}
}
// I simply call the above in the onClick handler in a button
<button onClick={handleExcelExport}> Export excel </button>
I can see that a download file appears when I click on the button but I can't open it. MS Excel says that ""File format or file extension is not valid..."
I fixed by changing to the following in the BE:
const binaryWorkbook = write(workbook, {
type: "array",
bookType: "xlsx",
});
and also adding headers per the docs:
res.setHeader(
"Content-Disposition",
'attachment; filename="SheetJSNode.xlsx"'
);
res.setHeader("Content-Type", "application/vnd.ms-excel");
Then in the frontend I changed the response type and content-type to
{
responseType: "arraybuffer",
}
Blob content-type
const blob = new Blob([response], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});

React: How to open PDF in new Tab from Cloud storage without downloading in local pc

I am trying to open pdf from the cloud in a new tab, without downloading it to the local machine.
I tried this way but not working for me. In the new tab, it is giving an error.
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
const pdfWindow = window.open();
pdfWindow.location.href = fileURL;
})
.catch((error) => {
console.log(error);
});
}

Download pdf from REST API with correct encoding

I'm trying to download pdf file from rest api using those two methods:
download(): ng.IPromise<Blob> {
return this.$http.get<ArrayBuffer>(this.urls.getUrl())
.then(response => {
return new Blob([response.data], {type: 'application/pdf'});
}
)
}
this.service.download().then( file => {
var a = document.createElement("a"),
url = URL.createObjectURL(file);
open(url)
a.href = url;
a.download = 'invoice';
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
And there appears to be some problem with the encoding of created Blob. If I call this endpoint from Postman and select "save response" then "save to a file", I get the correct pdf. When I use the presented code, file seems to be incorrectly encoded (opened with vim has generally similar structure, but different symbols).
In service you can use httpOptions like this:
download() {
const httpOptions = {
responseType: 'blob' as 'json',
};
return this.http.get<any>(
ServerUrl + `/api/getfile`,
httpOptions
);
}
also on you component you can call service and download the pdf like this:
this.api.download().subscribe(
(idata) => {
let blob = new Blob([idata], { type: 'application/pdf'
});
var downloadURL = window.URL.createObjectURL(idata);
var link = document.createElement('a');
link.href = downloadURL;
link.download = 'invoice.pdf';
link.click();
},
async (err) => {
}
);

How to set content type while uploading a file

I am uploading a file to s3 bucket. While the uploading need to find file extension and need to add it correct content type.
$('#upload-files').on('click', function(e) {
e.preventDefault();
var fileName = data.files[0].name;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if (ext == "pdf") {
console.log(data);
data.submit();
} else {
alert("Upload Pdf images only");
return false;
}
})
How to add its content-type before upload.
This code will help you to send data to server:
public formdata = new FormData();
onSubmit() {
this.resetform(); //Order matters here
let headers: any = new Headers();
headers.append('Content-type', 'undefined');
formData.append("selectFile", this.formData);
const req5 = new HttpRequest('POST', 'url as hosted on TOMCAT', formData,
reportProgress: true,
responseType: 'text'
});
return this.httpClient.request(req5).subscribe(e => {
(console.log(e);)
}
}
resetform() {
this.formData = new FormData();
}

cordovaFile.readAsArrayBuffer ENCODING_ERR

I'm trying to use $cordovaFile.readAsArrayBuffer but I'm getting the following error
I tried some solutions from the forum but without success
function getFileBlob(url, cb) {
console.log(url);
var path = url.substring(0, url.lastIndexOf('/') + 1);
var filename = url.substring(url.lastIndexOf('/') + 1, url.length);
console.log('path', path);
console.log('file', filename);
$cordovaFile.readAsArrayBuffer(path, filename)
.then(function (success) {
var blob = new Blob([success], { type: 'image/jpeg' });
cb(blob);
}, function (error) {
onsole.error(error);
cb(null);
});
}
Error:
FileError code:5, message:"ENCODING_ERR"
Console.logs:
My url: /file:///storage/emulated/0/Android/data/com.ionicframework.xx443164/cache/.Pic.jpg
var path:/file:///storage/emulated/0/Android/data/com.ionicframework.xx443164/cache/
var file: .Pic.jpg
I'm testing on an android
I think this can help you, if you need to get your photo as a blob type
var photo = url; // your photo
var mainDic = photo.substring(0, photo.lastIndexOf('/') + 1),
mainArchive = photo.substring(photo.lastIndexOf('/') + 1, photo.length);
$cordovaFile.readAsArrayBuffer(mainDic, mainArchive).then(function(success) {
var blob = new Blob([success], {
type: 'image/jpeg'
});
// now blob is your photo as blob type
}, function(error) {
console.error(error);
});

Categories

Resources