File download in angular js - android

How to download a file in a mobile device while giving the URL from the server, In Angularjs mobile application(Platform Cordova). The file can be of type pdf, image etc...

You have to do something like this:
This is Angular JS part:
import { Http, ResponseContentType } from '#angular/http';
...
constructor(
private http: Http,
) { }
downloadFile() {
return this.http
.get('http://www.africau.edu/images/default', {
responseType: ResponseContentType.Blob,
search: // query string if have
})
.map(res => {
return {
filename: 'sample.pdf',
data: res.blob()
};
})
.subscribe(res => {
console.log('start download:',res);
var url = window.URL.createObjectURL(res.data);
var a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = url;
a.download = res.filename;
a.click();
window.URL.revokeObjectURL(url);
a.remove(); // remove the element
}, error => {
console.log('download error:', JSON.stringify(error));
}, () => {
console.log('Completed file download.')
});
}
This is HTML part:
<button class="btn btn-primary" (click)="downloadFile()"><i class="fa fa-file-pdf-o"></i> Download</button>

Related

Display image from internal storage in Vue + Cordova

I am trying to display an image from download folder.
imagePath: file:///storage/emulated/0/Download/sample.png
Set Image URL:
window.resolveLocalFileSystemURL(this.imagePath, function success(fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function() {
if (this.result) {
var blob = new Blob([new Uint8Array(this.result)], { type: "image/png" });
this.imgUrl = window.URL.createObjectURL(blob);
}
};
reader.readAsArrayBuffer(file);
});
}, function (err) {
this.info = 'An error was found: '+ err;
});
Display it on UI:
<img class="img-fluid" src="{{imgUrl}}" />
But code is not reaching inside onloadend callback.

react-native How to open local file url using Linking?

I'm using the following code to download a file (can be a PDF or a DOC) and then opening it using Linking.
const { dirs } = RNFetchBlob.fs;
let config = {
fileCache : true,
appendExt : extension,
addAndroidDownloads : {
useDownloadManager : false,
notification : false,
title : 'File',
description : 'A file.',
path: `${dirs.DownloadDir}/file.${extension}`,
},
};
RNFetchBlob.config(config)
.fetch(
method,
remoteUrl,
APIHelpers.getDefaultHeaders()
)
.then((res) => {
let status = res.info().status;
if (status == 200) {
Linking.canOpenURL(res.path())
.then((supported) => {
if (!supported) {
alert('Can\'t handle url: ' + res.path());
} else {
Linking.openURL(res.path())
.catch((err) => alert('An error occurred while opening the file. ' + err));
}
})
.catch((err) => alert('The file cannot be opened. ' + err));
} else {
alert('File was not found.')
}
})
.catch((errorMessage, statusCode) => {
alert('There was some error while downloading the file. ' + errorMessage);
});
However, I'm getting the following error:
An error occurred while opening the file. Error: Unable to open URL:
file:///Users/abhishekpokhriyal/Library/Developer/CoreSimulator/Devices/3E2A9C16-0222-40A6-8C1C-EC174B6EE9E8/data/Containers/Data/Application/A37B9D69-583D-4DC8-94B2-0F4AF8272310/Documents/RNFetchBlob_tmp/RNFetchBlobTmp_o259xexg7axbwq3fh6f4.pdf
I need to implement the solution for both iOS and Android.
I think the easiest way to do so is by using react-native-file-viewer package.
It allows you to Prompt the user to choose an app to open the file with (if there are multiple installed apps that support the mimetype).
import FileViewer from 'react-native-file-viewer';
const path = // absolute-path-to-my-local-file.
FileViewer.open(path, { showOpenWithDialog: true })
.then(() => {
// success
})
.catch(error => {
// error
});
So, I finally did this by replacing Linking by the package react-native-file-viewer.
In my APIHelpers.js:
async getRemoteFile(filePath, extension, method = 'GET') {
const remoteUrl = `${API_BASE_URL}/${encodeURIComponent(filePath)}`;
const { dirs } = RNFetchBlob.fs;
let config = {
fileCache : true,
appendExt : extension,
addAndroidDownloads : {
useDownloadManager : false,
notification : false,
title : 'File',
description : 'A file.',
path: `${dirs.DownloadDir}/file.${extension}`,
},
};
return new Promise(async (next, error) => {
try {
let response = await RNFetchBlob.config(config)
.fetch(
method,
remoteUrl,
this.getDefaultHeaders()
);
next(response);
} catch (err) {
error(err);
}
});
}
In my Actions.js
export function openDocument(docPath, ext) {
return async (dispatch) => {
dispatch(fetchingFile());
APIHelpers.getRemoteFile(docPath, ext).then(async function(response) {
dispatch(successFetchingFile());
let status = response.info().status;
if (status == 200) {
const path = response.path();
setTimeout(() => {
FileViewer.open(path, {
showOpenWithDialog: true,
showAppsSuggestions: true,
})
.catch(error => {
dispatch(errorOpeningFile(error));
});
}, 100);
} else {
dispatch(invalidFile());
}
}).catch(function(err) {
dispatch(errorFetchingFile(err));
});
}
}
In my Screen.js
import { openDocument } from 'path/to/Actions';
render() {
return <Button
title={'View file'}
onPress={() => this.props.dispatchOpenDocument(doc.filepath, doc.extension)}
/>;
}
.
.
.
const mapDispatchToProps = {
dispatchOpenDocument: (docPath, ext) => openDocument(docPath, ext),
}
Are you downloading it from the web? I can see the pdf path is attached at the end of the error path.
For web URLs, the protocol ("http://", "https://") must be set accordingly!
Try to append appropriate schemes to your path. Check it out from the link mentioned below.
This can be done with 'rn-fetch-blob'
RNFetchBlob.android.actionViewIntent(fileLocation, mimeType);

How to display images returned by Cordova PhotoLibrary?

I seem to have trouble displaying images in the Image Gallery on Android. The PhotoLibrary plugin returns the list of files, but when I feed the image URLs to img tags, they don't load.
window['cordova']['plugins']['photoLibrary'].getLibrary(
result => console.log(libraryItem),
err => console.log(err);
},
{
thumbnailWidth: 512,
thumbnailHeight: 384,
quality: 0.8,
includeAlbumData: true
});
This will retrieve the URLs to the images, but they can't be used to actually display them. I get things like:
creationDate: Fri Nov 03 2017 20:06:01 GMT-0400 (EDT)
fileName: "2017-10-4-1.jpg"
height: 960
id: "1907;/storage/emulated/0/Pictures/Timelapser/2017-10-4-1.jpg"
latitude: 0
longitude: 0
photoURL: "cdvphotolibrary://photo?photoId=1907%3B%2Fstorage%2Femulated%2F0%2FPictures%2FTimelapser%2F2017-10-4-1.jpg"
thumbnailURL: "cdvphotolibrary://thumbnail?photoId=1907%3B%2Fstorage%2Femulated%2F0%2FPictures%2FTimelapser%2F2017-10-4-1.jpg&width=512&height=384&quality=0.8"
width: 1280
Feeding photoURL or thumbnailURL to img src doesn't work. I tried to decodeURI them, use the part before or after the ; and nothing.
You need to use Native Photo Library plugin and cdvphotolibrary pipe as shown below.
Here is working Git project
html
<ion-grid no-padding margin-top>
<ion-row class="row">
<ion-col col-6 *ngFor="let data of library">
<img [src]="data?.thumbnailURL | cdvPhotoLibrary">
</ion-col>
</ion-row>
</ion-grid>
ts
//fetch Photos
fetchPhotos() {
this.platform.ready().then(() => {
this.library = [];
this.photoLibrary.getLibrary({ thumbnailWidth: THUMBNAIL_WIDTH, thumbnailHeight: THUMBNAIL_HEIGHT }).subscribe({
next: (chunk) => {
this.library = this.library.concat(chunk);
this.cd.detectChanges();
},
error: (err: string) => {
if (err.startsWith('Permission')) {
this.platform.ready().then(() => {
this.photoLibrary.requestAuthorization({ read: true })
.then(() => {
}).catch((err) => {
let message = 'requestAuthorization error: ${err}';
this.showToast.showErrorToast(message);
});
});
} else { // Real error
let message: 'getLibrary error: ${err}';
this.showToast.showErrorToast(message);
}
},
complete: () => {
// Library completely loaded
}
});
});
}
cdv-photo-library.ts (pipe)
import { Pipe, PipeTransform } from '#angular/core';
import { DomSanitizer } from '#angular/platform-browser';
#Pipe({
name: 'cdvPhotoLibrary',
})
export class CdvPhotoLibraryPipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) { }
transform(url: string) {
if (url != null) {
return url.startsWith('cdvphotolibrary://') ? this.sanitizer.bypassSecurityTrustUrl(url) : url;
}
}
}

react-native upload pictures on android

I have a react-native app on Android and a backend server written in NodeJS + Express and I'm using multer to handle file uploads.
const multer = require('multer');
const mime = require('mime');
const crypto = require('crypto');
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, config.uploads),
filename: (req, file, cb) => {
crypto.pseudoRandomBytes(16, (err, raw) => {
cb(null, raw.toString('hex') + Date.now() + '.' + mime.extension(file.mimetype));
});
}
});
const upload = multer({ storage });
const Router = require('express').Router;
const controller = require('./upload.controller');
const router = new Router();
const auth = require('./../../auth/auth.service');
router.post('/', [auth.isAuthenticated(), upload.any()], controller.create);
module.exports = router;
And on my react-native app I try to do like this:
ImagePicker.launchCamera(options, image => {
let { uri } = image
const API_URL = 'http://192.168.1.2:9000/api/uploads'
var form = new FormData();
form.append("FormData", true)
form.append("access_token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjU3YjgyZGQ2MTEwZDcwYmEwYjUxZjM5YyIsImlzTWVkaWMiOnRydWUsImlhdCI6MTQ3MTY4ODE1MiwiZXhwIjoxNDcxNzA2MTUyfQ.gPeql5g66Am4Txl1WqnbvOWJaD8srTK_6vihOJ6kFbY")
form.append("Content-Type", "image/jpg")
form.append('image', uri)
fetch(API_URL, {body: form, mode: "FormData", method: "post", headers: {"Content-Type": "multipart/form-data"}})
.then((response) => console.log(response))
.catch((error) => {
console.log("ERROR " + error)
})
.then((responseData) => {
console.log("Succes "+ responseData)
})
.done();
})
But when I try to upload I recive the following error
multipart body must have at least one part
I am doing something wrong?
Does anybody knows a better solution to do this?
Fetch may not support Blob and FormData at this moment, but you can use XMLHttpRequest polyfill instead.
let xhr = new XMLHttpRequest()
xhr.open('post', `http://myserver.com/upload-form`)
xhr.send(form)
xhr.onerror = function(e) {
console.log('err', e)
}
xhr.onreadystatechange = function() {
if(this.readyState === this.DONE) {
console.log(this.response)
}
}

ngcordova android file select and upload to server

I want to upload file from my ionic application to server. I am using cordovafiletransfer plugin. Using that I am able to upload file by providing static path in controller code. My question is how to get selected file path by user? I only get filename from input tag on the relative path of selected file. How to get that?
View Page Code:
<label class="item item-input">
<div class="input-label">Upload Photo</div>
<input type="file" onchange="angular.element(this).scope().setFile(this)" accept="image/*"/>
</label>
<div class="padding">
<button ng-click="upload()" class="button button-block button-assertive">Upload</button>
</div>
Controller Code:
$scope.upload = function() {
var filename, options, targetPath;
console.log($scope.theFile);
targetPath = cordova.file.externalRootDirectory + '/Download/androidify.png';
filename = targetPath.split('/').pop();
options = {};
options.fileKey = 'image_file';
options.fileName = $scope.theFile.name;
options.chunkedMode = false;
options.mimeType = $scope.theFile.type;
options.headers = {
'Authorization': getDeviceToken()
};
console.log(options);
return $cordovaFileTransfer.upload(domain.uploadphoto(), targetPath, options).then(
(function(result) {
console.log('SUCCESS: ' + JSON.stringify(result.response));
}),
(function(err) {
console.log('ERROR: ' + JSON.stringify(err));
}),
function(progress) {}
);
};
$scope.setFile = function(element) {
return $scope.$apply(function($scope) {
console.log(element);
return $scope.theFile = element.files[0];
});
};
How to get proper target path of selected file?
I came across this post which should solve the problem, (it works for me, with some modification):
In my template:
<input type="file" fileread="file.path" />
<button type="button" class="button button-small button-assertive" ng-click="vm.upload(file)">Upload PDF</button>
and my modified Directive:
.directive("fileread", ['$cordovaFile', function ($cordovaFile) {
return {
scope: {
fileread: "="
},
link: function (scope, element, attributes) {
element.bind("change", function (changeEvent) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
var fileName = changeEvent.target.files[0].name;
$cordovaFile.writeFile(cordova.file.dataDirectory, fileName, loadEvent.target.result, true)
.then(function (result) {
console.log(result)
}, function (err) {
console.warn(err)
});
scope.$apply(function () {
scope.fileread = cordova.file.dataDirectory + fileName;
});
}
reader.readAsArrayBuffer(changeEvent.target.files[0]);
});
}
}
}]);
Remember to clean up after you uploaded the document
use:
$cordovaFile.removeFile(cordova.file.dataDirectory, fileName)
.then(function (success) {
// success
}, function (error) {
// error
});
Also see http://www.javascripture.com/FileReader for more info regarding FileReader

Categories

Resources