Skip to content

Instantly share code, notes, and snippets.

@coolvasanth
Last active April 3, 2020 05:40
Show Gist options
  • Save coolvasanth/b266c5bb382ddbfc60ca1c0f7c9f33c0 to your computer and use it in GitHub Desktop.
Save coolvasanth/b266c5bb382ddbfc60ca1c0f7c9f33c0 to your computer and use it in GitHub Desktop.
choosing .jpg,.pdf,.docs etc files from galley and uploading it to server via your API using IONIC 2. (DOESN'T WORK ON IOS)
// Install file chooser and file transfer API from ionic 2 and import them into your page.ts. and don't forget to add providers in
app.component.ts
import { Component } from '@angular/core';
import { NavController, NavParams} from 'ionic-angular';
import { Home } from '../../homemodule/home';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { UserProfileService } from '../../services/login.service';
import { ConfirmidentityPage } from '../confirmidentity/confirmidentity';
import { ProgressDialog } from '../../utility/progress-dialog';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { Transfer, FileUploadOptions, TransferObject } from '@ionic-native/transfer';
import { FileChooser } from '@ionic-native/file-chooser';
constructor(public navCtrl: NavController,
public navParams: NavParams,
private builder: FormBuilder,
private userProfileService: UserProfileService,
private progressDialog: ProgressDialog,
private transfer: Transfer,
private camera: Camera,
private fileChooser: FileChooser
) {}
uploadresume()
{
this.fileChooser.open()
.then(uri =>
{
console.log(uri)
const fileTransfer: TransferObject = this.transfer.create();
// regarding detailed description of this you cn just refere ionic 2 transfer plugin in official website
let options1: FileUploadOptions = {
fileKey: 'image_upload_file',
fileName: 'name.pdf',
headers: {},
params: {"app_key":"Testappkey"},
chunkedMode : false
}
fileTransfer.upload(uri, 'your API that can take the required type of file that you want to upload.', options1)
.then((data) => {
// success
alert("success"+JSON.stringify(data));
}, (err) => {
// error
alert("error"+JSON.stringify(err));
});
})
.catch(e => console.log(e));
}
@shafiqshams
Copy link

What to do for IOS ??

@coolvasanth
Copy link
Author

coolvasanth commented Oct 16, 2017

Sorry for late response. As you might be aware unlike Android, iOS will not give direct access to its file system. All the documents will be stored in drive kind of application (like google drive, iCloud etc). So choosing a file in iOS means choosing a file from cloud applications. I have created a gist that explains how to choose a file in iOS.. https://gist.github.com/coolvasanth/d042a26deda75f5e390b42b87995f30d

@jessicastorm1986
Copy link

Can you please provide complete code, html and server side php aswell. Been 3 days, trying to achieve file upload from ionic. Till now unable to achieve it

@jessicastorm1986
Copy link

When i am trying to upload, i am getting this error - https://stackoverflow.com/questions/49343993/ionic-3-file-select-and-upload-giving-error , please help if possible

@coolvasanth
Copy link
Author

@jessicastorm1986 I'm very sorry for the late reply. You could have commented on the stackoverflow, I would have replied back to you. As git hub is not giving notifications for gist. Let me know, if you still have any queries, will try to resolve it.

@Manjunath-p
Copy link

@coolvasanth it's working fine.but it' not taking system files like pdf and doc etc, in mobile devices please help me

@coolvasanth
Copy link
Author

@Manjunath-p are you able to chose media files like image, video etc ? or let me know what other type of files you are able to chose ?

@Manjunath-p
Copy link

ya i am able to choose all media types but document files are not upload from system files

@coolvasanth
Copy link
Author

@Manjunath-p, clarify me, you are facing trouble in uploading the files or choosing? Meanwhile look at this repository of mine, it may help you.
https://github.com/coolvasanth/upload-multiple-image-files-in-Ionic-3-4

@Manjunath-p
Copy link

Manjunath-p commented Aug 28, 2019

@coolvasanth what you have sent that link is not working it takes only images not pdf and doc

@coolvasanth
Copy link
Author

Hi @Manjunath-p ideally file-chooser plugin should allow you to choose every possible file. Why don't you try putting the file mime type filter as mentioned here and check ? https://github.com/ihadeed/cordova-filechooser . Even if this doesn't work, kindly share your code to chose the file.

@Manjunath-p
Copy link

@coolvasanth thank you working fine. let me know how to select the multiple file and how to extract the file extensions in code

@coolvasanth
Copy link
Author

@Manunath-p, please refer this link: https://github.com/coolvasanth/upload-multiple-image-files-in-Ionic-3-4. You can easily chose multiple file and upload with it.

@alabiboo
Copy link

@coolvasanth thank you working fine. I use the same method to upload a pdf and word file but it doesn't work. But on the other hand it works for uploading image files. What can this be due to? please i use ionic 3

@coolvasanth
Copy link
Author

Why don't you try this ? https://github.com/coolvasanth/upload-multiple-image-files-in-Ionic-3-4. You will be able to upload all types of files with this. Let me know, still if you face any problem.

@alabiboo
Copy link

Thanks for your help @coolvasanth. I just used your code but this piece of code "
this.base64.encodeFile(filePath).then(
(base64File) => {
console.log("BASE 64 IS", filePath.split(".").pop());
console.log(base64File);
if (isImage == false) {
this.fileArray.push({
displayFile: filePath.split("/").pop(),
base64File: base64File.split(",").pop() //split(",").pop() depends on the requirement, if back end API is able to extract
//the file mime type then you can do this, if back end expects UI update the Mime type
// then don't use split(",").pop()
});
} else {
this.imageArr.push({
displayImg: filePath,
base64Img: base64File.split(",").pop() //same comment for image follows here.
});
}
console.log("LENGTH OF BASE64ARR", this.fileArray.length);
},
err => {
console.log(err);
}
);
" does not convert the file to base64 .

this massage is captured => console.log("BASE 64 IS", filePath.split(".").pop());
but console.log(base64File); don't display anything

@alabiboo
Copy link

hi @coolvasanth, i realize that the base64 plugin of ionic 3 is still in beta version. I tried to use filetransfer to upload a pdf file but without success. if you once use the ionic 3 filetransfer plugin, your help will be welcome

@coolvasanth
Copy link
Author

Hi Alabiboo, sorry for the delayed response. As you might aware cordova-file-transfer is a old plugin, it doesn't have any support now, so I would suggest you, avoid using that. Base 64 plugin should work, if it not working, then can you kindly give explanation about the device, Ionic and NodeJS version ?

@alabiboo
Copy link

alabiboo commented Apr 1, 2020

Hi @coolvasanth,
Android version 8.1
Ionic version 3.20.1
NodeJS version v10.0.0

@coolvasanth
Copy link
Author

Hi @alabiboo, all the things look fine, have you tried the execution on multiple devices ? you have said that console.log(base64File); don't display anything. Can you check in the chrome inspector during the API call, does it contains the base64 parameter ? As Bae64 string is very long, sometimes inspector fail to render it.

@alabiboo
Copy link

alabiboo commented Apr 1, 2020

Okay! yes, it is chrome inspector that I use. if I select an image file, console.log(base64File); displays a too long string, but if I select a pdf file, nothing is displayed. I try to display the content of base64File before calling the API.

@coolvasanth
Copy link
Author

Okay, you don't have a problem with Base 64 then, all you have is problem with choosing the PDF. Can you please add the code for choosing the PDF ? And sample output after choosing PDF ?

@alabiboo
Copy link

alabiboo commented Apr 2, 2020

Okay,

chooseFileForAndroid() {
this.filechooser
.open()
.then(uri => {
this.filePath
.resolveNativePath(uri)
.then(filePath => {
console.log(filePath);
this.convertToBase64(filePath,false);
})
.catch(() => {
console.log('Error reading path');
});
})
.catch(e => {
console.log(e);
});
}

after choosing the pdf,
console.log(filePath); displayed file:///storage/emulated/0/Download/CSC73010-Assignment-2-S3-2019 (1).pdf

@coolvasanth
Copy link
Author

Hi @alabiboo the same code is working for me. Anyways I tried a alternative for you, kindly have a look at below.

  1. Install File plugin from here > https://ionicframework.com/docs/native/file/
  2. let base64PDF = await this.file.readAsDataURL(pdfFilePath, pdfFilename);

This also worked for me. Let me know your feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment