How to solve File (.pdf) path directory doesn't exist error if I select file (.pdf) from mobile download folder in ionic - ionic-framework

I want to upload the pdf file on our server using the file-chooser Cordova plugin. I had success in the file selection but after the file selection I tried to upload on the server but received the error "directory doesn't exist".
var filter = { "mime": "application/pdf" };
this.fileChooser.open(filter)
.then(url => {
console.log('fileChooser:',url);
this.filePath.resolveNativePath(url)
.then(filePath => {
console.log('saif file pathhh',filePath);
let correctPath = url.substr(0,url.lastIndexOf("/") + 1);
let currentName = filePath.substring(filePath.lastIndexOf('/') + 1);
this.file.checkDir(this.file.externalDataDirectory, correctPath).then(_ => console.log('Directory exists')).catch(err =>
console.log('Directory doesnt exist'));
let _filePath = filePath;
let resPath = this.pathForImage(_filePath);
let newEntry = {
name: currentName,
path: resPath,
filePath: _filePath,
comparessedPath: _filePath,
};
this.startUpload(newEntry, index, field_id);
})
.catch(err => console.log('saif file pathhh errorrr',err));
})
.catch(e => {
console.log('saif file pathhh errorrr catchhh',e);
});
I want to real path of selected pdf file by using file-chooser cordova plugin

Related

ionic 3 capacitor return file paths from document directory

Ionic 3 capacitor on ios.
I have stored jpeg files in the AppData Documents directory. Now I want to display the images. The images are displayed in the HTML with
img src="{{image2}}" ( one option )
This is my working code, it returns the actual path to the file ( based in part on Josh Morony 'ionic capacitor photo save', in part on capacitor source code FileSystem API) :
fileName1 = "photo2.jpeg";
Filesystem.getUri({
directory: FilesystemDirectory.Data,
path: fileName1
}).then((result) => {
this.image1 = result.uri.replace('file://', '_capacitor_');
}, (err) => {
console.log(err);
});
fileName2 = "photo2.jpeg";
Filesystem.getUri({
directory: FilesystemDirectory.Data,
path: fileName2
}).then((result) => {
this.image2 = result.uri.replace('file://', '_capacitor_');
}, (err) => {
console.log(err);
});
fileName3 = "photo3.jpeg";
Filesystem.getUri({
directory: FilesystemDirectory.Data,
path: fileName3
}).then((result) => {
this.image3 = result.uri.replace('file://', '_capacitor_');
}, (err) => {
console.log(err);
});
example of path returned in this.image: capacitor/var/mobile/Containers/Data/Application/1C408C3C-
DB30-47C1-3416-6FB2697DC7AF/Documents/photo2.jpeg
I have 20 photos in the Documents directory; the names of the photos in an array = ["photo1.jpeg","photo2.jpeg","photo3.jpeg"," ...];
I can repeat the code above 20 times and get 20 paths, but I would like to refactor the code so that the code returns an array of 20 paths. I do not know how to achieve that in ionic 3.

Cordova Ionic Native File plugin - Where does it store the files in iOS?

I been trying to save a file on iOS. Right now I been running through Xcode right to my phone.
When I run the app it says that is saved successfully. But I don’t see any file when I use a file manager app like FileApp, FileManager, iCloud and the Apple crappy Files app.
My question is that I heard from a web search that in order to save the file iOS creates a sandbox folder for the app.
If I been saving it to this.file.documentDirectory, how can a user open it in let’s say Pages or Numbers apps? (You know Apple’s Word and Excel replacement for the uninitiated.)
Here’s the code.
writeToIOS(opts : {
fileName: string,
text: any
}) : Promise < IResponse < any >> {
let response: IResponse < boolean > = {
success: false,
error: '',
data: false
};
const options: IWriteOptions = {
replace: true
};
return new Promise((resolve, reject) => {
const path = this.file.documentsDirectory;
const directory = 'Attendance Log';
this
.file
.checkDir(path, directory)
.then(res => {
this
.file
.writeFile(path + directory, opts.fileName, opts.text, options)
.then(res => {
response = {
...response,
success: true,
error: res,
data: res
};
resolve(response);
})
.catch(error => reject(error));
})
.catch(() => {
this
.file
.createDir(path, directory, true)
.then(directory => {
this
.file
.writeFile(path + directory.name, opts.fileName, opts.text, options)
.then(res => {
response = {
...response,
success: true,
error: res,
data: res
};
resolve(response);
})
.catch(error => reject(error));
})
.catch(error => reject(error));
});
});
}
EDIT:
What the client/user should do is be able to choose the file and open it in his/her favorite app. That being a File Manager app or a Writer or Spreadsheet app.
I don't have too much experience with iOS, but I think you have chosen good dir.
cordova.file.documentsDirectory - Files private to the app, but that
are meaningful to other application (e.g. Office files). Note that for
OSX this is the user's ~/Documents directory. (iOS, OSX)
In iOS i would search /var/mobile/Applications/<UUID>/Documents
This is using the cordova-plugin-fileopener2 in conjuction with ionic native file opener:
const options = {
replace: true
};
const path = this.file.documentsDirectory;
const directory = 'Attendance Log';
this.file
.checkDir(path, directory)
.then(res => {
this.file
.writeFile(path + directory, opts.fileName, opts.text, options)
.then(res => {
this.fileOpener
.open(`${path}${directory}/${opts.fileName}` , 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
.then(() => ...)
.catch(error => ...);
})
.catch(error => ...);

cordova camera plugin issue with FILE_URI

I am using IONIC 3.7.0 in my current project. In one requirement I need to use cordova camera plugin to take photo uri from image gallery. Every time when I am trying to get the URI , I get the data_uri which is base64 long string.
I only need the file_uri of image to go further. Please suggest.
var options = {
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
destinationType: Camera.DestinationType.FILE_URI
};
Camera.getPicture(options)
.then((imageData) => {
console.log(imageData);
this.fileToUpload = imageData;
const base64Image = "data:image/jpeg;base64," + imageData;
this.preloadImage._img.src = base64Image;
this.codeservice.doProfileImageUpload(base64Image)
.subscribe(res => {
if(res.length()>0){
console.log('updated');
}
})
}, (err) => {
console.log(err);
});

Ionic native file opener 2 error class not found

I receive error when trying to open a file Class not found
.ts
open(){
this.platform.ready().then(() => {
this.fileOpener.open(this.entry.nativeURL, this.attachment.mime).then(() => {
console.log('file opened')
}, err => {
console.log('error open file: ', err)
});
});
}
this.entry.nativeURL is the download result using File Transfer
nativeURL: file:///storage/emulated/0/Download/someFile.docx
this.fileTransfer.download(url, this.storageDirectory + this.attachment.fileName, trustAllHosts).then((entry) => {
console.log('entry: ', entry);
this.entry = entry;
}
this.attachment.mime: application/vnd.openxmlformats-officedocument.wordprocessingml.document
I also tried application/pdf for a pdf file , didn't work
Its working... the problem was in running the app live --livereload

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().