How to insert image in sqlite? - javascript

I am developing a cross platform application using cordova.
I need to insert image inside sqlite. I am getting lots of code for android but I find it difficult to do with javascript. I am getting err.code:5 when I run the following code in my iPhone.
document.addEventListener("deviceready", onDeviceReady, false);
var img;
var currentRow;
var b = new Blob();
function previewFile() {
// var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
// var package_name = document.getElementById("pr").value;
reader.onloadend = function () {
// img = reader.result;
if(file.type.match('image.*'))
{
img = reader.result;
// ref.push({"image":image,"service":arr,"package_name":package_name});
}
else
{
alert("select an image file");
}
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
var image1 = encodeURI(img);
// var b = new Blob();
b = image1;
console.log(b);
console.log(image1);
//document.write('<img src="'+image+'"/>');
}
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase({name:"sqlite"});
db.transaction(populateDB, errorCB, successCB);
}
function populateDB(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id INTEGER PRIMARY KEY AUTOINCREMENT, name,number,image BLOB)');
}
function insertDB(tx) {
tx.executeSql('INSERT INTO DEMO (name,number,image) VALUES ("' +document.getElementById("txtName").value
+'","'+document.getElementById("txtNumber").value+'","' +b+ '")');
}
function goInsert() {
var db = window.sqlitePlugin.openDatabase({name:"sqlite"});
db.transaction(insertDB, errorCB, successCB);
}
My html code:
<input type="file" onchange="previewFile()">
<button onclick="goInsert()">Insert</button>
How to do this. Can someone help me? Thanks in advance...

Convert your image (in memory) to a byte[] and then save it your sql db as varbinary(max).

Inserting blob into database will make your application slow as well as laggy, instead save the path of the selected picture into the database.
And when you want to upload the image to the server use
fileupload feature of cordova.
If you are getting image from server than download that image locally and save that path into the database
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function onFileSystemSuccess(fileSystem)
{
fileSystem.root.getFile(
"dummy.html", {create : true, exclusive : false},
function gotFileEntry(fileEntry)
{
var sPath = fileEntry.fullPath.replace("dummy.html", "");
var fileTransfer = new FileTransfer();
fileEntry.remove();
fileTransfer.download(
"http://www.w3.org/2011/web-apps-ws/papers/Nitobi.pdf",
sPath + "theFile.pdf",
function(theFile)
{
console.log("download complete: " + theFile.toURI());
showLink(theFile.toURI());
},
function(error)
{
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code: " + error.code);
}
);
}, fail);
}, fail);

Related

Using File System as source of videos for playing offline

I am trying to add offline functionality to my HTML5 video player. I am attempting to write the files into the chrome file system as a blob and then read them from there. I believe that I am running into an issue where the files are not actually being written, just the file name. As my below code is currently constituted, it works, though still only if it is permanently connected to the internet. My goal is to have the files download to a persistent directory in the filesystem and then continue to play if the internet is disconnected.
$(document).ready(function() {
var dir = "http://www.kevmoe.com/networks/gsplayer/";
var fileextension = ".mp4";
var srcfiles = $.ajax({
//This will retrieve the contents of the folder if the folder is configured as 'browsable'
url: dir,
success: function(data) {
//List all .mp4 file names in the page
$(data).find("a:contains(" + fileextension + ")").each(function() {
var filename = $(this).attr("href").replace(window.location.host, "").replace("http://", "");
$("#container").append("<div id='div1' class='video'><video id='video1' class='vidarray' preload='none' poster='bkg.png'><source src='" + filename + "' type='video/mp4'></video></div>");
async: false;
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTANT, 200000 * 1024 * 1024, initFS, errorHandler);
function initFS(fs) {
console.log('filesystem engaged'); // Just to check if everything is OK :)
// place the functions you will learn bellow here
function errorHandler(err) {
var msg = 'An error occured: ';
};
function createDir(rootDir, folders) {
rootDir.getDirectory(folders[0], {
create: true
}, function(dirEntry) {
if (folders.length) {
createDir(dirEntry, folders.slice(1));
}
}, errorHandler);
};
createDir(fs.root, 'files/video/'.split('/'));
fs.root.getDirectory('video', {}, function(dirEntry) {
var dirReader = dirEntry.createReader();
dirReader.readEntries(function(entries) {
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
if (entry.isDirectory) {
console.log('Directory: ' + entry.fullPath);
} else if (entry.isFile) {
console.log('File: ' + entry.fullPath);
}
}
}, errorHandler);
}, errorHandler);
fs.root.getFile(filename, {
create: true,
exclusive: true
}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
var blob = new Blob([data], {
type: 'video/mp4'
});
fileWriter.write(blob);
}, errorHandler);
console.log('file downloaded');
}, errorHandler);
//Try to add an event listener for when all files are finished loading into file system. Then use another function to source the videos locally.
var dirReader = fs.root.createReader();
var entries = [];
// Call the reader.readEntries() until no more results are returned.
dirReader.readEntries(function(results) {
//List all .mp4 file names in the page
$(results).find("a:contains(" + fileextension + ")").each(function() {
var filename = $(this).attr("href").replace(window.location.host, "").replace("http://", "");
$("#container").append("<div id='div1' class='video'><video id='video1' class='vidarray' preload='none' poster='bkg.png'><source src='" + filename + "' type='video/mp4'></video></div>");
async: false;
}, errorHandler);
});
};
function errorHandler() {
console.log('An error occured');
};
});
var videos = $('.video');
//handle ending of video
videos.find('video').on('ended', function() {
playNextVideo(videos);
});
// start with the first one
playNextVideo(videos);
function playNextVideo(videoList) {
var activeVideo = videoList.filter('.active').removeClass('active'), // identify active video and remove active class
activeIndex = videoList.index(activeVideo), // get the active video index in the group
nextVideo = videoList.eq(activeIndex + 1), // get the next video in line
actualVideo;
// if there is no next video start from first
if (nextVideo.length == 0) nextVideo = videoList.first();
// pause all videos
videoList.find('video').each(function() {
this.pause();
})
// get reference to next video element
actualVideo = nextVideo.find('video').get(0);
// add active class to next video
nextVideo.addClass('active');
// load and play
actualVideo.volume = 0.04;
actualVideo.load();
actualVideo.play();
}
}
});
});
filesystem: protocol stores files with reference to same origin as document which requests LocalFileSystem. That is, if JavaScript at Question is created at, for example, http://example.org, the path to LocalFileSystem should be same origin as http://example.org, not file: protocol.
If you are trying to store files or folders for accessing at file: protocol, offline, you can create an .html document to use as a template bookmark.
Visit the local .html file once while online to get files and populate LocalFileSystem. If navigator.onLine is true, navigate to http://example.org, else get and process files and folders stored at LocalFileSystem.
Create a list as JSON or JavaScript Array to store list of files to fetch, instead of parsing an .html document for file locations.
Store local file as a bookmark. Launch Chromium, Chrome with --allow-file-access-from-files flag set to access filesystem: protocol from file: protocol and file: protocol at filesystem: protocol, if not online.
<!DOCTYPE html>
<html>
<head>
<title>LocalFileSystem Offline Videos Bookmark</title>
</head>
<body>
<script>
// location to visit if online
const onLineURL = "https://lorempixel.com/"
+ window.innerWidth
+ "/"
+ window.innerHeight + "/cats";
const props = {
requestedBytes: 1024 * 1024 * 20000,
folder: "videos",
// list of files to fetch for offline viewing
mediaList: [
"http://mirrors.creativecommons.org/movingimages/webm/"
+ "ScienceCommonsJesseDylan_240p.webm"
, "https://nickdesaulniers.github.io/netfix/demo/frag_bunny.mp4"
]
};
let grantedBytes = 0;
function getLocalFileSystem ({requestedBytes = 0, mediaList=[], folder = ""}) {
if (!requestedBytes || !mediaList.length || !folder) {
throw new Error("requestedBytes: Number"
+ " or mediaList: Array"
+ " or folder: String not defined");
};
// do stuff with `filesystem:` URL
function processLocalFilePath(localPath) {
const video = document.createElement("video");
document.body.appendChild(video);
video.controls = true;
video.src = localPath;
}
function errorHandler(err) {
console.log(err);
}
function writeFile(dir, fn, fp, localPath) {
console.log(dir, fn, fp, localPath);
dir.getFile(fn, {}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
// do stuff when file is written
console.log(e.type, localPath + " written");
window.webkitResolveLocalFileSystemURL(localPath
, function(file) {
// file exists in LocalFileSystem
processLocalFilePath(localPath);
}, errorHandler)
};
fileWriter.onerror = errorHandler;
fetch(fp).then(function(response) {
return response.blob()
}).then(function(blob) {
fileWriter.write(blob);
}).catch(errorHandler)
}, errorHandler);
}, errorHandler);
}
if (mediaList && mediaList.length) {
navigator.webkitTemporaryStorage.requestQuota(requestedBytes
, function(grantedBytes_) {
grantedBytes = grantedBytes_;
console.log("Requested bytes:", requestedBytes
, "Granted bytes:", grantedBytes);
window.webkitRequestFileSystem(window.TEMPORARY
, grantedBytes
, function(fs) {
const url = fs.root.toURL();
mediaList.forEach(function(filename) {
const localPath = url + folder + "/"
+ filename.split("/").pop();
window.webkitResolveLocalFileSystemURL(localPath
, function(file) {
// file exists in LocalFileSystem
console.log(localPath + " exists at LocalFileSystem");
processLocalFilePath(localPath)
}, function(err) {
console.log(err, localPath
+ " not found in LocalFileSystem");
// Exception is thrown if file
// or folder path not found
// create `folder` directory, get files
fs.root.getDirectory(folder, {}
, function(dir) {
writeFile(dir
, filename.split("/").pop()
, filename
, localPath);
}),
errorHandler
})
})
})
}, errorHandler)
}
}
if (location.href !== onLineURL && navigator.onLine) {
location.href = onLineURL;
} else {
getLocalFileSystem(props);
}
</script>
</body>
</html>
See also
How to use webkitRequestFileSystem at file: protocol
How to print all the txt files inside a folder using java script
Read local XML with JS
How to Write in file (user directory) using JavaScript?
An alternative approach could be to utilize ServiceWorker
Adding a Service Worker and Offline into your Web App
Service Worker Sample: Custom Offline Page Sample
Your user must grant your app permission to store data locally before your app can use persistent storage.
That's why you have to request quota first. The amount of bytes you ask for is 200000 * 1024 * 1024 bytes.
window.storageInfo.requestQuota(PERSISTENT, 200000 * 1024 * 1024,
function(grantedBytes) {
window.requestFileSystem(window.PERSISTENT, grantedBytes, onInitFs, errorHandler);
},
errorHandler
);
MDN documentation
I noticed you are writing this for Chrome, here's how you manage the quota in Chrome

Uploading Files to Dropbox using Dropbox API V2 + Corodva

Has anyone been able to upload files to Dropbox using Javascript SDK for Dropbox (Link to Dropbox javascript SDK) API V2 in Cordova Application? I had a look at the Dropbox-sdk.js file for method to upload files but all the methods require content of the file we want to upload to dropbox More about Upload methods here. How do we provide the content of the files?
The examples from the Javascript Sdk use input type file element to get the files to be uploaded to the Dropbox. But in case of Cordova how to do it? How can we pass the contents of the file?
Below is my code to upload File to Dropbox but when I try to open the uploaded file it show pdf file with no contents.
function uploadFile(tmpStrListStr)
{
var tmpStrList = "";
var uploadSuccess = false;
tmpStrList = tmpStrListStr.substring(0, tmpStrListStr.length-1).split(",");
istrue = true;
for(var i = 0 ; i < tmpStrList.length; i++)
{
var path = cordova.file.externalRootDirectory+'/Test/Logs/'+tmpStrList[i] + '.pdf';
window.resolveLocalFileSystemURL(path, function (fileEntry) {
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onloadend = function(e) {
var ACCESS_TOKEN = localStorage.accessToken;
var dbx = new Dropbox({ accessToken: ACCESS_TOKEN });
var fileCommitInfo = {};
fileCommitInfo.contents = reader.result;
fileCommitInfo.path = '/' + fileEntry.name;
fileCommitInfo.mode = { '.tag': 'overwrite' };
fileCommitInfo.autorename = true;
fileCommitInfo.mute = true;
dbx.filesUpload(fileCommitInfo)
.then(function(response) {
alert(response);
})
.catch(function(errr) {
console.log(errr);
});
}
reader.readAsDataURL(file);
});
}, function (e) {
console.log("FileSystem Error");
console.dir(e);
});
}
}
Is there any other way to implement the Dropbox feature(API V2) for Cordova Applications without using Javascript SDK?
Is there anyone in this whole world who can tell me how to upload the files to Dropbox using Javascript SDK V2?
To read the contents of a file used XMLHttpRequest. From the response, created a blob object and then set it to contents parameter of the FilesUpload method.
function UploadNewFile() {
var rawFile = new XMLHttpRequest();
rawFile.responseType = 'arraybuffer';
rawFile.open("GET", "Your file Path Here", true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var blobObj = new Blob([rawFile.response],{ type: 'application/pdf',endings: 'native' });
dbx = new Dropbox({accessToken: "Your Access Token"});
if (dbx != null) {
dbx.filesUpload({
path:'/' + "File Name Here"+ '.pdf',
contents: blobObj,
mode: 'overwrite',
mute: true
}).then(function (response) {
var showmsg = "File Upload Complete";
reset();
alertify.alert(showmsg, function (e)
{
if (e)
{
//Code to be executed after your files are successfully uploaded to Dropbox.
}
});
}
}).catch(function (error) {
var showmsg = "Error saving file to your Dropbox!";
reset();
alertify.alert(showmsg);
});
};
}
}
}
rawFile.send(null);
}
Reference:What is blob?

Cordova - download image from URL to the pictures gallery

I created a simple cordova android app and I am trying to download an image from an URL to the pictures gallery, but I really can't figure out what is going wrong.
I have already searched a lot here in stackoverflow, including the following links:
Phonegap - Save image from url into device photo gallery
How to save an Image object into a file in Android with Phonegap?
I have installed cordova File Transfer plugin and tried to do the example from the official site, but it didn't work too: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file-transfer/
I tried 2 different codes, which are:
1) First attempt:
document.getElementById("myBtn").addEventListener("click", function () {
download("http://cordova.apache.org/static/img/cordova_bot.png", "data", "new_file");
});
function download(URL, Folder_Name, File_Name) {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, fileSystemSuccess, fileSystemFail);
function fileSystemSuccess(fileSystem) {
var download_link = encodeURI(URL);
ext = download_link.substr(download_link.lastIndexOf('.') + 1); //Get extension of URL
var directoryEntry = fileSystem.root; // to get root path of directory
directoryEntry.getDirectory(Folder_Name, {
create: true,
exclusive: false
}, onDirectorySuccess, onDirectoryFail); // creating folder in sdcard
var rootdir = fileSystem.root;
var fp = rootdir.toURL();
fp = fp + "/" + Folder_Name + "/" + File_Name + "." + ext; // fullpath and name of the file which we want to give
filetransfer(download_link, fp);
}
function onDirectorySuccess(parent) {
// Directory created successfuly
}
function onDirectoryFail(error) {
alert("Unable to create new directory: " + error.code);
}
function fileSystemFail(evt) {
//Unable to access file system
alert(evt.target.error.code);
}
}
function filetransfer(download_link, fp) {
var fileTransfer = new FileTransfer();
fileTransfer.download(download_link, fp,
function (entry) {
alert("download complete: " + entry.fullPath);
//cordova.plugins.imagesaver.saveImageToGallery(entry.fullPath, successCallback, errorCallback);
},
function (error) {
alert("download error source " + error.source);
}
);
}
In this attempt, I get the alert message "download complete: /my_folder/new_file.png" but I can't find where the picture is downloaded.
It is definitely not in the pictures gallery or anywhere I can find it.
2) Second attempt:
function download() {
window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024, function (fs) {
var url = 'http://cordova.apache.org/static/img/cordova_bot.png';
fs.root.getFile('downloaded-image.png', {
create: true,
exclusive: false
}, function (fileEntry) {
file_transfer(fileEntry, encodeURI(url), true);
}, onErrorCreateFile);
}, onErrorLoadFs);
}
function onErrorLoadFs(msg){
alert(msg);
}
function onErrorCreateFile(msg){
alert(msg);
}
function file_transfer(fileEntry, uri, readBinaryData) {
var fileTransfer = new FileTransfer();
var fileURL = fileEntry.toURL();
fileTransfer.download(
uri,
fileURL,
function (entry) {
alert("download complete: " + entry.toURL());
if (readBinaryData) {
// Read the file...
readBinaryFile(entry);
} else {
// Or just display it.
displayImageByFileURL(entry);
}
},
function (error) {
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("upload error code" + error.code);
},
null, // or, pass false
{
//headers: {
// "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
//}
}
);
}
In this attempt, I get the alert message "download complete: file:///data/user/0/com.companyname.xxxxxxx/cache/downloaded-image.png", but I also can't find the picture anywhere in the device.
I have already tried the application in two different android devices.
This is how I did it.
you will need the cordova file plugin
it wil take a url(png in my case)
and it will save it in your download folder (which makes it apear in the gallery of your phone)
//download file to device
function DownloadToDevice(fileurl) {
var blob = null;
var xhr = new XMLHttpRequest();
xhr.open("GET", fileurl);
xhr.responseType = "blob";//force the HTTP response, response-type header to be blob
xhr.onload = function()
{
blob = xhr.response;//xhr.response is now a blob object
console.log(blob);
var storageLocation = "";
switch (device.platform) {
case "Android":
storageLocation = 'file:///storage/emulated/0/';
break;
case "iOS":
storageLocation = cordova.file.documentsDirectory;
break;
}
var folderpath = storageLocation + "Download";
var filename = "Myimg.png";
var DataBlob = blob;
window.resolveLocalFileSystemURL(folderpath, function(dir) {
dir.getFile(filename, {create:true}, function(file) {
file.createWriter(function(fileWriter) {
fileWriter.write(DataBlob);
//Download was succesfull
}, function(err){
// failed
console.log(err);
});
});
});
}
xhr.send();
}
You should change the line
window.requestFileSystem(window.TEMPORARY, 5 * 1024 * 1024,
->
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
and
if download success, you should re-scan your device storage, because Cordova does not know if the file is downloaded.
so i made a plugin ,
It is a plugin that updates the gallery after downloading.
https://github.com/pouu69/cordova-plugin-gallery-refresh
If you are still looking for solution try this working plugin for android
cordova plugin add cordova-plugin-downloadimage-to-gallery
I use this function with callbacks.
To check the different types of cordovaFileSystem see here or check the ones available to you by typing in the console console.log(cordova.file)
downloadFileToDevice('https://example.com/image.jpg', 'myimg.jpg', cordova.file.cacheDirectory,
(err, filePath) => {
if (err) {
console.log('An error was found: ', err)
} else {
console.log('file downloaded successfully to: ' + filePath)
}
})
Function declaration
function downloadFileToDevice (fileurl, filename, cordovaFileSystem, callback) {
var blob = null
var xhr = new XMLHttpRequest()
xhr.open('GET', fileurl)
xhr.responseType = 'blob' // force the HTTP response, response-type header to be blob
xhr.onload = function () {
blob = xhr.response // xhr.response is now a blob object
var DataBlob = blob
window.resolveLocalFileSystemURL(cordovaFileSystem, function (dir) {
dir.getFile(filename, { create: true }, function (file) {
file.createWriter(function (fileWriter) {
fileWriter.write(DataBlob)
callback(null, cordovaFileSystem + filename)
}, function (err) {
callback(err)
})
})
})
}
xhr.send()
}

Cordova App : How to get the actual path of file

I'm using Cordova to make android and iOS app, now I would like to check if file already exist in the dirctory.
First I download file from server and save it locally using the code below
$scope.downloadFile = function(){
alert(cordova.file.dataDirectory)
var fileTransfer = new FileTransfer();
var uri = encodeURI("http://example.com/files/th/001.mp3");
var downloadPath = cordova.file.dataDirectory+'001.mp3'; // ANDROID
fileTransfer.download(
uri,
downloadPath,
function(entry) {
$scope.savepath = entry.toInternalURL();
alert("download complete: " + entry.toURL());
alert('saved at : '+entry.toInternalURL());
},
function(error) {
alert("download error source " + error.source);
alert("download error target " + error.target);
alert("upload error code" + error.code);
},
false,
{
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
}//End DownloadFile
and I would like to check if the file already exist using checkIfFileExists(path) method
function checkIfFileExists(path){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem){
//alert('result: '+JSON.stringify(fileSystem.root))
fileSystem.root.getFile(path, { create: false }, fileExists, fileDoesNotExist);
}, getFSFail); //of requestFileSystem
}
function fileExists(fileEntry){
alert("File " + fileEntry.fullPath + " exists!");
}
function fileDoesNotExist(){
alert("file does not exist");
}
function getFSFail(evt) {
console.log(evt.target.error.code);
}
I checked on my phone, the file is already saved to Android/data/com.myname.myappname/file/001.mp3
but the problem is the code always show file does not exist whenever I use the path like
cordova.file.dataDirectory+'001.mp3';
or cdvfile://localhost/persistent/files/001.mp3
or 'cdvfile://localhost/files/001.mp3'
so I would like to ask that the real path that I need to use to check if the file exist or not.
Please provide me any suggestion.
Regards.
Do you need to use or CheckFileExists? You could try using Phonegap's FileReader method?
var reader = new FileReader();
var fileSource = cordova.file.dataDirectory+'001.mp3'
reader.onloadend = function(evt) {
if(evt.target.result == null) {
// Null? You still have a problem: file doesn't exist.
} else {
// Otherwise the file exists.
}
};
//Check if the file exists
reader.readAsDataURL(fileSource);

How to get path from html5 input field file object for phonegap

How do you get a path from a file object which is returned from an html5 input field?
Basically the phonegap app is setup to go online and download a sound file from a thirdparty website, then browse to the downloaded file and move it to the local directory. (short < 1 sec sound files).
The problem is that file objects attribute .fullPath is undefined. and getFile takes a path input, not an [object File] input.
From the following code:
<input style="opacity:0;" type="file" name="soundInput" id="soundInput"/>
<script type="text/javascript" charset="utf-8">
var soundInput = document.getElementById('soundInput');
soundInput.addEventListener('change', function(){handleFileSelect(type);}, false);
soundInput.click();
function handleFileSelect() {
var file = this.files[0]; // FileList object
var type = isThumpy;
alert("file = " + file.name + "\n full path = " + file.fullPath);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
gotFS(fs,file,type);
}, fail);
}
function fail(error) {
alert("error " + error.code);
}
function gotFS(fileSystem, file, type) {
alert("got filesystem");
var flags = {create: false, exclusive: false};
fileSystem.root.getFile(file, flags, function(fe){
gotFileEntry(type,fe);
},fail);
}
function gotFileEntry(type, fileEntry) {
alert("got fileEntry");
fileEntry.copyTo(path, function(fe){successfulCopy(type, fe);}, fail);
}
function successfulCopy(type, fileEntry) {
alert("copy success");
setSoundByUri(type, fileEntry.name)
}
</script>
It doesn't get past "got filesystem", and it doesn't throw an error ("error " + error.code). Please help.
You can not get the path data from a file input. File inputs are read only. Try changing the approach. Use the phoneGap fileEntry to create the new file and write data from the file input to it.
like this:
<script type="text/javascript" charset="utf-8">
function handleFileSelect(type) {
var file = this.files[0]; // FileList object
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
gotFS(fs,file,type);
}, fail);
}
function gotFS(fileSystem, file, type) {
var flags = {create: true, exclusive: false};
fileSystem.root.getFile(file.name, flags, function(fe) {gotFileEntry(fe, file, type);}, fail);
}
function gotFileEntry(fileEntry, file, type) {
fileEntry.createWriter(function(w){gotFileWriter(w, file, type);}, fail);
}
function gotFileWriter(fileWriter, file, type) {
fileWriter.onwriteend = function(evt){setSoundByUri(type, path + file.name);};
var reader = new FileReader();
reader.onload = function(event) {
var rawData = event.target.result;
fileWriter.write(rawData);
};
reader.onerror = function(event){
alert("error, file could not be read" + event.target.error.code);
};
reader.readAsArrayBuffer(file);
}
function fail(error) {
alert("error " + error.code);
if (error.code == FileError.PATH_EXISTS_ERR){
alert("The file already exists.");
}
}
</script>

Categories

Resources