file transfer not working non media files in Android 11 - ionic-framework

file transfer not working non media files in Android 11(how handle scoped storage in ionic 3)
var targetPath = this.file.externalDataDirectory+'ido/'+date.toISOString().split('T')[0]+'/'+name; this.fileTransfer.download(url, targetPath,true).then((entry) => { console.log('download complete: ' + entry.toURL()); });

Related

Download pdf file from firebase storage ioinc 5

I am trying to download pdf file in ionic 5 application, which is stored in firebase storage i tried using filetransfer but file not downloading in my device it gives entry url this
file:///data/user/0/io.ionic.starter/files/test.pdf
Here the Download function
download(downloadUrl: string) {
console.log(downloadUrl);
this.fileTransfer.download(downloadUrl,this.file.dataDirectory +'test.pdf').then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
});
}
You need to add
android:requestLegacyExternalStorage="true"
inside AndroidMenifest.xml > application tag like below screenshot. It's required to add in the android 11 version.

Recorded file neither saving nor playing in cordova-plugin-media (Error code 1)

I'm using this plugin: cordova-plugin-media with ionic capacitor instead of cordova with command ionic cap sync.
My code:
audioFile: MediaObject;
constructor(private media: Media, private plt: Platform, private file: File) {}
ionViewDidEnter() {
this.plt.ready()
.then(() => {
setTimeout(() => {
this.audioFile = this.media.create(this.file.externalRootDirectory + 'audiofile.mp3');
this.audioFile.onStatusUpdate.subscribe(status => console.log('status: ', status));
this.audioFile.onSuccess.subscribe(() => console.log('Action is successful'));
this.audioFile.onError.subscribe(error => console.log('Error: ', error));
}, 1000);
})
.catch(err => console.log('ready error: ', err));
}
record() {
// When record button clicked
this.audioFile.startRecord();
}
stop() {
// When stop button clicked
this.audioFile.stopRecord();
this.audioFile.play();
}
When I clicked Record btn, record() was executed and output was: Error: 1 and when I stopped recording than the output was status: 4 and Action is successful
I expected to either play the recording or get audiofile.mp3 in the file manager of my android device but I didn't observed any of it. Can someone help me with this issue?
What I tried:
I thought that its extension issue so I tried replacing mp3 with 3gp and m4a
I tried removing file:// from file.externalRootDirectory with slice method - file.externalRootDirectory.slice(7)
Instead of externalRootDirectory I also tried applicationDirectory and externalDataDirectory
I also submitted my issue on their github repository but I didn't got any response yet
I tried finding solutions on other communities and stackoverflow itself but problem still exists
Android 10 uses a new file system therefore plugins that have not updated themselves might not read/create files on Android 10.
You need to manually add this line in your manifest file : android:requestLegacyExternalStorage="true"
Open your project in Android Studio and open the AndroidManifest file.
In tag inside your manifest file, add android:requestLegacyExternalStorage="true"
Rebuild your project

How can i check if file exist with ionic

i am building a mobile app for both android and iOS i want to check if a directory exist in the users sd card or in-built memory, if the directory doesn't exist, then i will create the directory.
I checked the docs on ionic file transfer docs but i can't find anything useful, i searched online but found some code but its not working, the name of the directory that I want to create is softik, Here is the code
public storageDirectory:any;
download() {
this.chkmkDir().then(async ()=>{
const fileTransfer: FileTransferObject = this.fileTransfer.create();
this.storageDirectory = `${this.file.externalRootDirectory}test.mp4`;
fileTransfer.onProgress((progressEvent)=>this.progress=Math.round((progressEvent.loaded / progressEvent.total) * 100))
fileTransfer.download(this.url,this.storageDirectory + 'test.mp4', true).then((entry) =>
console.log('Berhasil download dan tersimpan di : ' + this.storageDirectory + "test.jpeg"),
error => console.log('gagal : ' + JSON.stringify(error)),
);
}).catch(err=>console.log())
}
chkmkDir(){
return new Promise((resolve, reject)=>{
this.file.checkDir(this.file.externalRootDirectory, 'softik').then(res=>resolve()
).catch(err => {
this.file.createDir(this.file.externalRootDirectory, 'softik',false).then(res =>resolve())
.catch(err=>reject(JSON.stringify(err)));
});
})
}
Pls what am i going wrong
first you should use File plugin
then you can search for file or Directory
see this docs https://ionicframework.com/docs/v3/native/file/#checkFile

How to Read Data from OBDII in Ionic 3?

I need a way to connect data from Bluetooth using Ionic 3 to retrieve data.
I now use the code as an example:
this.bluetoothSerial.write(this.code).then( (success) => {
alert('Connected ' + '. Data reading is successful: ' + new Uint8Array(success));
},

Sails.js checking stuff before uploading files to MongoDB with skipper (valid files, image resizing etc)

I'm currently creating a file upload system in my application. My backend is Sails.js (10.4), which serves as an API for my separate front-end (Angular).
I've chosen to store the files I'm uploading to my MongoDB instance, and using sails' build in file upload module Skipper. I'm using the adapter skipper-gridfs (https://github.com/willhuang85/skipper-gridfs) to upload the files to mongo.
Now, it's not a problem to upload the files themselves: I'm using dropzone.js on my client, which sends the uploaded files to /api/v1/files/upload. The files will get uploaded.
To achieve this i'm using the following code in my FileController:
module.exports = {
upload: function(req, res) {
req.file('uploadfile').upload({
// ...any other options here...
adapter: require('skipper-gridfs'),
uri: 'mongodb://localhost:27017/db_name.files'
}, function(err, files) {
if (err) {
return res.serverError(err);
}
console.log('', files);
return res.json({
message: files.length + ' file(s) uploaded successfully!',
files: files
});
});
}
};
Now the problem: I want to do stuff with the files before they get uploaded. Specifically two things:
Check if the file is allowed: does the content-type header match the file types I want to allow? (jpeg, png, pdf etc. - just basic files).
If the file is an image, resize it to a few pre-defined sizes using imagemagick (or something similar).
Add file-specific information that will also be saved to the database: a reference to the user who has uploaded the file, and a reference to the model (i.e. article/comment) the file is part of.
I don't have a clue where to start or how to implement this kind of functionality. So any help would be greatly appreciated!
Ok, after fiddling with this for a while I've managed to find a way that seems to work.
It could probably be better, but it does what I want it to do for now:
upload: function(req, res) {
var upload = req.file('file')._files[0].stream,
headers = upload.headers,
byteCount = upload.byteCount,
validated = true,
errorMessages = [],
fileParams = {},
settings = {
allowedTypes: ['image/jpeg', 'image/png'],
maxBytes: 100 * 1024 * 1024
};
// Check file type
if (_.indexOf(settings.allowedTypes, headers['content-type']) === -1) {
validated = false;
errorMessages.push('Wrong filetype (' + headers['content-type'] + ').');
}
// Check file size
if (byteCount > settings.maxBytes) {
validated = false;
errorMessages.push('Filesize exceeded: ' + byteCount + '/' + settings.maxBytes + '.');
}
// Upload the file.
if (validated) {
sails.log.verbose(__filename + ':' + __line + ' [File validated: starting upload.]');
// First upload the file
req.file('file').upload({}, function(err, files) {
if (err) {
return res.serverError(err);
}
fileParams = {
fileName: files[0].fd.split('/').pop().split('.').shift(),
extension: files[0].fd.split('.').pop(),
originalName: upload.filename,
contentType: files[0].type,
fileSize: files[0].size,
uploadedBy: req.userID
};
// Create a File model.
File.create(fileParams, function(err, newFile) {
if (err) {
return res.serverError(err);
}
return res.json(200, {
message: files.length + ' file(s) uploaded successfully!',
file: newFile
});
});
});
} else {
sails.log.verbose(__filename + ':' + __line + ' [File not uploaded: ', errorMessages.join(' - ') + ']');
return res.json(400, {
message: 'File not uploaded: ' + errorMessages.join(' - ')
});
}
},
Instead of using skipper-gridfs i've chosen to use local file storage, but the idea stays the same. Again, it's not as complete as it should be yet, but it's an easy way to validate simple stuff like filetype and size. If somebody has a better solution, please post it :)!
You can specify a callback for the .upload() function. Example:
req.file('media').upload(function (error, files) {
var file;
// Make sure upload succeeded.
if (error) {
return res.serverError('upload_failed', error);
}
// files is an array of files with the properties you want, like files[0].size
}
You can call the adapter, with the file to upload from there, within the callback of .upload().