Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created February 1, 2020 16:42
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save prof3ssorSt3v3/2455efaed9f2f98a76449038ccbd3753 to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/2455efaed9f2f98a76449038ccbd3753 to your computer and use it in GitHub Desktop.
Cordova File Plugin Video Code
/**
* cordova create [folder] [packagename] [app name]
*
* cordova platform add ios
* cordova platform add android
*
* cordova plugin add cordova-plugin-camera --variable CAMERA_USAGE_DESCRIPTION="your usage message" --variable PHOTOLIBRARY_USAGE_DESCRIPTION="your usage message"
* cordova plugin add cordova-plugin-file
*
* navigator.camera.getPicture(success, fail, options)
* success(fileuri)
*
* resolveLocalFileSystemURL(path, success, fail)
*
* success returns either
* directoryEntry
* .getDirectory(name, {create:true}, success, fail)
* .getFile("newFile.txt", {create: true}, success, fail)
* fileEntry
* .isFile
*
* which inherit from
* Entry
* .nativeURL - absolute device OS path to file. entry.toURL() method
* .fullPath - relative to the HTML root
* .toInternalURL() - returns a cdvfile:// path
* Add <access origin="cdvfile://*" /> to config.xml
* Add cdvfile: to your Content-Security-Policy
* .name
* .type
* .copyTo()
* .remove()
*
* cordova.file.dataDirectory - save your permanent files here
* cordova.file.applicationDirectory + "www/" - your www folder for your Cordova project
*
* https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-camera/index.html
* https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/index.html
*
* Error Codes for Files
* https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/index.html#list-of-error-codes-and-meanings
* Writing to a file
* https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/index.html#write-to-a-file
*/
const app = {
tempURL: null,
permFolder: null,
oldFile: null,
permFile: null,
KEY: "OLDfileNAMEkey",
init: () => {
setTimeout(function() {
console.log("File system/plugin is ready");
app.addListeners();
//create the folder where we will save files
app.getPermFolder();
}, 2000);
},
addListeners: () => {
document.getElementById("btnCam").addEventListener("click", app.takePic);
document.getElementById("btnFile").addEventListener("click", app.copyImage);
},
getPermFolder: () => {
let path = cordova.file.dataDirectory;
//save the reference to the folder as a global app property
resolveLocalFileSystemURL(
path,
dirEntry => {
//create the permanent folder
dirEntry.getDirectory(
"images",
{ create: true },
permDir => {
app.permFolder = permDir;
console.log("Created or opened", permDir.nativeURL);
//check for an old image from last time app ran
app.loadOldImage();
},
err => {
console.warn("failed to create or open permanent image dir");
}
);
},
err => {
console.warn("We should not be getting an error yet");
}
);
},
loadOldImage: () => {
//check localstorage to see if there was an old file stored
let oldFilePath = localStorage.getItem(app.KEY);
//if there was an old file then load it into the imgFile
if (oldFilePath) {
resolveLocalFileSystemURL(
oldFilePath,
oldFileEntry => {
app.oldFileEntry = oldFileEntry;
let img = document.getElementById("imgFile");
img.src = oldFileEntry.nativeURL;
},
err => {
console.warn(err);
}
);
}
},
takePic: ev => {
ev.preventDefault();
ev.stopPropagation();
let options = {
quality: 80,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.CAMERA,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
mediaType: Camera.MediaType.PICTURE,
targetWidth: 400,
targetHeight: 400
};
console.log(options);
navigator.camera.getPicture(app.gotImage, app.failImage, options);
},
gotImage: uri => {
app.tempURL = uri;
document.getElementById("imgCamera").src = uri;
},
failImage: err => {
console.warn(err);
},
copyImage: ev => {
ev.preventDefault();
ev.stopPropagation();
//copy the temp image to a permanent location
let fileName = Date.now().toString() + ".jpg";
resolveLocalFileSystemURL(
app.tempURL,
entry => {
//we have a reference to the temp file now
console.log(entry);
console.log("copying", entry.name);
console.log(
"copy",
entry.name,
"to",
app.permFolder.nativeURL + fileName
);
//copy the temp file to app.permFolder
entry.copyTo(
app.permFolder,
fileName,
permFile => {
//the file has been copied
//save file name in localstorage
let path = permFile.nativeURL;
localStorage.setItem(app.KEY, path);
app.permFile = permFile;
console.log(permFile);
console.log("add", permFile.nativeURL, "to the 2nd image");
document.getElementById("imgFile").src = permFile.nativeURL;
//delete the old image file in the app.permFolder
if (app.oldFile !== null) {
app.oldFile.remove(
() => {
console.log("successfully deleted old file");
//save the current file as the old file
app.oldFile = permFile;
},
err => {
console.warn("Delete failure", err);
}
);
}
},
fileErr => {
console.warn("Copy error", fileErr);
}
);
},
err => {
console.error(err);
}
);
}
};
const ready = "cordova" in window ? "deviceready" : "DOMContentLoaded";
document.addEventListener(ready, app.init);
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
html {
font-size: 20px;
line-height: 1.7;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}
body {
min-height: 100vh;
width: 100vw;
overflow-x: hidden;
}
.app {
padding: 0;
width: 100vw;
min-height: 100vh;
}
.app p {
width: 100%;
padding: 1rem 5vw;
}
.app img {
width: 90vw;
height: 90vw;
object-fit: contain;
}
.app button {
background-color: cornflowerblue;
color: white;
width: 90vw;
font-size: 1.2rem;
display: block;
margin: 0.5rem auto;
}
<!DOCTYPE html>
<html>
<head>
<!--
Customize this policy to fit your own app's needs. For more guidance, see:
https://github.com/apache/cordova-plugin-whitelist/blob/master/README.md#content-security-policy
Some notes:
* gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
* https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
* Disables use of inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
* Enable inline JS: add 'unsafe-inline' to default-src
-->
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;"
/>
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta
name="viewport"
content="initial-scale=1, width=device-width, viewport-fit=cover"
/>
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Camera and File Plugin</title>
</head>
<body>
<div class="app">
<p>
Image from the Camera <br />
<img src="" alt="image from camera" id="imgCamera" />
</p>
<button id="btnCam">Click to Take Picture</button>
<button id="btnFile">Click to Copy File</button>
<p>
Image from the File System<br />
<img src="" alt="image from file system" id="imgFile" />
</p>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment