Access sd card in android for uploading a file to my php server using phonegap - file-upload

I want to go to select a file from sdcard and upload it to server. is it possible to access the sdcard in android via phonegap as how we are picking a image from gallery and uploading. I went through samples but all are specifying the file name also like eg: mnt/sdcard/read.txt. But i want to goto only sdcard so that user can select his own file is it possible to do.

U can easily do that its very easy
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccessUpload, fail);
function onFileSystemSuccessUpload(fileSystem) {
// get directory entry through root and access all the folders
var directoryReader = fileSystem.root.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(successReader,fail);
}
function successReader(entries) {
var i;
for (i=0; i<entries.length; i++) {
//alert(entries[i].name);
if(entries[i].isDirectory==true)
{
var directoryReaderIn = entries[i].createReader();
directoryReaderIn.readEntries(successReader,fail);
}
if(entries[i].isFile==true)
{
entries[i].file(uploadFile, fail);
}
}
};
function uploadFile(file) {
var target=""; //the url to upload on server
var ft = new FileTransfer(),path = "file://"+ file.fullPath,name = file.name;
ft.upload(path, target, win, fail, { fileName: name });
// var ft = new FileTransfer();
//ft.upload(file.fullPath, target, win, fail, options);
function win(r) {
alert("Code = " + r.responseCode);
alert("Response = " + r.response);
alert("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
}
}

Related

Sending audio file created with RecordRTC to my server

I am new to working with Javascript, PHP, and with servers generally. I am working on a web page that will record audio from the user and save it to my server, using RecordRTC. I'm a bit confused about the XMLHttpRequest portion - how do I alter the following code to send to my server instead of the webrtc server?
function uploadToServer(recordRTC, callback) {
var blob = recordRTC instanceof Blob ? recordRTC : recordRTC.blob;
var fileType = blob.type.split('/')[0] || 'audio';
var fileName = (Math.random() * 1000).toString().replace('.', '');
if (fileType === 'audio') {
fileName += '.' + (!!navigator.mozGetUserMedia ? 'ogg' : 'wav');
} else {
fileName += '.webm';
}
// create FormData
var formData = new FormData();
formData.append(fileType + '-filename', fileName);
formData.append(fileType + '-blob', blob);
callback('Uploading ' + fileType + ' recording to server.');
makeXMLHttpRequest('https://webrtcweb.com/RecordRTC/', formData, function(progress) {
if (progress !== 'upload-ended') {
callback(progress);
return;
}
var initialURL = 'https://webrtcweb.com/RecordRTC/uploads/';
callback('ended', initialURL + fileName);
listOfFilesUploaded.push(initialURL + fileName);
});
}
Via my web hosting provider, I'm using an Apache server, phpMyAdmin, and a mySQL database. Do I just replace
makeXMLHttpRequest(https://webrtcweb.com/RecordRTC/
with "https://mywebsite.com" and replace
var initialURL = 'https://webrtcweb.com/RecordRTC/uploads/';
with the path to the file I created to hold these audio files (https://mywebsite.com/uploads)? Then set permissions for that folder to allow public write capabilities (this seems unsafe, is there a good method)?
This is the makeXMLHttpRequest function:
function makeXMLHttpRequest(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback('upload-ended');
}
};
request.upload.onloadstart = function() {
callback('Upload started...');
};
request.upload.onprogress = function(event) {
callback('Upload Progress ' + Math.round(event.loaded / event.total * 100) + "%");
};
request.upload.onload = function() {
callback('progress-about-to-end');
};
request.upload.onload = function() {
callback('progress-ended');
};
request.upload.onerror = function(error) {
callback('Failed to upload to server');
console.error('XMLHttpRequest failed', error);
};
request.upload.onabort = function(error) {
callback('Upload aborted.');
console.error('XMLHttpRequest aborted', error);
};
request.open('POST', url);
request.send(data);
}
Please make sure that your PHP server is running top over SSL (HTTPs)
Create a directory and name it uploadFiles
Create a sub-directory and name it uploads
Structure of the directories:
https://server.com/uploadFiles -> to upload files
https://server.com/uploadFiles/uploads -> to store files
index.php
Now create or upload following index.php file on this path: https://server.com/uploadFiles
<?php
// File Name: "index.php"
// via https://github.com/muaz-khan/RecordRTC/tree/master/RecordRTC-to-PHP
foreach(array('video', 'audio') as $type) {
if (isset($_FILES["${type}-blob"])) {
echo 'uploads/';
$fileName = $_POST["${type}-filename"];
$uploadDirectory = 'uploads/'.$fileName;
if (!move_uploaded_file($_FILES["${type}-blob"]["tmp_name"], $uploadDirectory)) {
echo(" problem moving uploaded file");
}
echo($fileName);
}
}
?>
Why sub-directory?
Nested directory uploads will be used to store your uploaded files. You will get URLs similar to this:
https://server.com/uploadFiles/uploads/filename.webm
Longer file upload issues:
https://github.com/muaz-khan/RecordRTC/wiki/PHP-Upload-Issues
upload_max_filesize MUST be 500MB or greater.
max_execution_time MUST be at least 10800 (or greater).
It is recommended to modify php.ini otherwise create .htaccess.
How to link my own server?
Simply replace https://webrtcweb.com/RecordRTC/ with your own URL i.e. https://server.com/uploadFiles/.

Titanium - Get image file from filesystem on Android

I have a problem getting an image from filesystem. On iOS works fine.
First of all, I save a remote image in the filesystem with this function:
img.imagen = url from the remote image (e.g. http://onesite.es/img2.jpeg)
function descargarImagen(img, callback){
var path = img.imagen;
var filename = path.split("/").pop();
var xhr = Titanium.Network.createHTTPClient({
onload: function() {
// first, grab a "handle" to the file where you'll store the downloaded data
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, filename);
f.write(this.responseData); // write to the file
Ti.API.debug("-- Imagen guardada: " + f.nativePath);
callback({path: f.nativePath});
},
timeout: 10000
});
xhr.open('GET', path);
xhr.send();
}
Now, I want to share this image creating an Android Intent:
args.image = f.nativePath(in the previous function)
var intent = null;
var intentType = null;
intent = Ti.Android.createIntent({
action: Ti.Android.ACTION_SEND
});
// add text status
if (args.status){
intent.putExtra(Ti.Android.EXTRA_TEXT, args.status);
}
// change type according to the content
if (args.image){
intent.type = "image/*";
intent.putExtraUri(Ti.Android.EXTRA_STREAM, args.image);
}else{
intent.type = "text/plain";
intent.addCategory(Ti.Android.CATEGORY_DEFAULT);
}
// launch intent
Ti.Android.currentActivity.startActivity(Ti.Android.createIntentChooser(intent, args.androidDialogTitle));
What I'm doing wrong?

Example code to use GridFS using mongoskin to upload file from form

I am using mongoskin to connect mongodb in my project. Now I have requirement to use GridFs to upload images, audio etc. I have one HTML form to upload these files.
I tried to find out example code to upload file using mongoskin however could't find any good one.
Please help.
After spending many hours; I am able to use mongoskin to upload file to Gridfs. Not sure if this is perfect code however sharing it here because I couldn't find any single working code on searching Google :-)
https://github.com/dilipkumar2k6/gridfs-mongoskin
var DBModule = require('./DBModule.js');
var Grid = require('gridfs-stream');
var mongoskin = require('mongoskin');
//Upload file to server and also update the database
exports.uploadContent = function (req, res) {
console.log('Calling uploadFile inside FileUploadService');
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
console.log('uploadFile after busboy fieldname: ' + fieldname + ", file : " + file + ", filename : " + filename);
// make sure the db instance is open before passing into `Grid`
var gfs = Grid(DBModule.db, mongoskin);
//Get metadata var host = req.headers['host'];
var metadata = {contentType: mimetype};
var writestream = gfs.createWriteStream({filename: filename, metadata: metadata});
file.pipe(writestream);
writestream.on('close', function (file) {
// return URL to acces the uploaded content
var path = "contents/" + file._id;
res.json({"path": path});
});
writestream.on('error', function (err) {
log.error({err: err}, 'Failed to upload file to database');
res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR);
res.json({error: err});
});
});
};
//view file from database
exports.previewContent = function (req, res) {
var contentId = new DBModule.BSON.ObjectID(req.params.contentid);
console.log('Calling previewFile inside FileUploadService for content id ' + contentId);
var gs = DBModule.db.gridStore(contentId, 'r');
gs.read(function (err, data) {
if (!err) {
//res.setHeader('Content-Type', metadata.contentType);
res.end(data);
} else {
log.error({err: err}, 'Failed to read the content for id ' + contentId);
res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR);
res.json({error: err});
}
});
};
Try this to store the data using gridfs (by default uses mongoskin). It worked for me.
var ObjectID = require('mongodb').ObjectID,
GridStore = require('mongodb').GridStore;
exports.saveMedia = function(db, media, next) {
console.log(media)
db.open(function (err, db) {
// Create a file and open it
var gridStore = new GridStore(db, new ObjectID(), "w");
gridStore.open(function (err, gridStore) {
// Write some content to the file
gridStore.write(new Buffer(media), function (err, gridStore) {
// Flush the file to db
gridStore.close(function (err, fileData)
//returns filename
next(null, fileData)
});
});
});
});
}

Apache Cordova File API via Windows Phone

I have tried to use Apache Cordova File Plugin documentation
Here is my code. It just basically goes through all folders into file system.
function log(text) {
var element = document.createElement('div');
element.innerHTML = text;
document.getElementById("log").appendChild(element);
}
function onSuccess(fileSystem) {
function printEntries(entries) {
log("Enter printEntries function");
var i;
log("Number of entries" + entries.length);
for (i = 0; i < entries.length; i++) {
log("Interation number " + i);
if (entries[i].isFile) {
log(entries[i].name);
} else {
log("Moving into subdirectory name: " + entries[i].name);
entries[i].createReader().readEntries(printEntries, fail);
}
}
}
function fail(error) {
log("Failed to list directory contents: " + error.code);
}
// Get a directory reader
var directoryReader = fileSystem.root.createReader();
// Get a list of all the entries in the directory
directoryReader.readEntries(printEntries, fail);
}
// request the persistent file system
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccess, null);
When I deploy my application to the my Lumia I have only this directories:
/
-Shared
---Media
---ShellContent
---Transfers
-debugOutput.txt
-DeviceID.txt
It seams that I have no access to files, that stored on my phone (images, videos).
So, my question is: Is it possible to get files from phone file system and sd card?

Win 8 Apps : saving and retrieving data in roamingfolder

I'm trying to store few user data into a roamingFolder method/property of Windows Storage in an app using JavaScript. I'm following a sample code from the Dev Center, but no success. My code snippet is as follows : (OR SkyDrive link for the full project : https://skydrive.live.com/redir?resid=F4CAEFCD620982EB!105&authkey=!AE-ziM-BLJuYj7A )
filesReadCounter: function() {
roamingFolder.getFileAsync(filename)
.then(function (filename) {
return Windows.Storage.FileIO.readTextAsync(filename);
}).done(function (data) {
var dataToRead = JSON.parse(data);
var dataNumber = dataToRead.count;
var message = "Your Saved Conversions";
//for (var i = 0; i < dataNumber; i++) {
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
//}
//counter = parseInt(text);
//document.getElementById("savedOutput2").innerText = dataToRead.counter;
}, function () {
// getFileAsync or readTextAsync failed.
//document.getElementById("savedOutput2").innerText = "Counter: <not found>";
});
},
filesDisplayOutput: function () {
this.filesReadCounter();
}
I'm calling filesDisplayOutput function inside ready method of navigator template's item.js file, to retrieve last session's data. But it always shows blank. I want to save upto 5 data a user may need to save.
I had some trouble running your code as is, but that's tangential to the question. Bottom line, you're not actually reading the file. Note this code, there's no then or done to execute when the promise is fulfilled.
return Windows.Storage.FileIO.readTextAsync(filename);
I hacked this in your example solution and it's working... typical caveats of this is not production code :)
filesReadCounter: function () {
roamingFolder.getFileAsync(filename).then(
function (filename) {
Windows.Storage.FileIO.readTextAsync(filename).done(
function (data) {
var dataToRead = JSON.parse(data);
var dataNumber = dataToRead.count;
var message = "Your Saved Conversions";
//for (var i = 0; i < dataNumber; i++) {
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
//}
//counter = parseInt(text);
//document.getElementById("savedOutput2").innerText = dataToRead.counter;
}, function () {
// readTextAsync failed.
//document.getElementById("savedOutput2").innerText = "Counter: <not found>";
});
},
function () {
// getFileAsync failed
})
},