Capture photo using navigator.camera or plain javascript - javascript

I want to take a photo by using device camera and it will be stored in the some type of thumbnail:
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
function onPhotoDataSuccessFront(imageData) {
var smallImageFront = document.getElementById('smallImageFront');
smallImageFront.style.display = 'block';
smallImageFront.src = "data:image/jpeg;base64," + imageData;
$('#btnFrontDiv').text('Retake Front');
}
As you can see I use navigator.camera which is avaliable in cordova/phonegap.
I want to capture photo by using cordova or plain javascript.
Thanks for any advice.

Try this one
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title> Cmaer</title>
<script type="text/javascript" src="cordova.js" ></script>
<script type="text/javascript">
var pictureSource,destinationType;
document.addEventListener("deviceready",loaded,false);
function loaded() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
function getPhoto(imageData) {
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = imageData;
}
function capturePhoto() {
navigator.camera.getPicture(getPhoto, onFail, { quality: 50 });
}
function onFail(message) {
alert('Failed because: ' + message);
}
</script>
</head>
<body>
<button onclick="capturePhoto();">Capture Photo</button> <br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
</body>
</html>
Reference

Capture and Upload image using phonegap
function uploadImage(){
navigator.camera.getPicture(uploadPhoto, onFailcapturePhoto, { quality: 50,destinationType: Camera.DestinationType.FILE_URI });
}
function onFailcapturePhoto(message) {
console.log("Message = " + message);
}
function uploadPhoto(imageURI) {
var imagefile = imageURI;
$('#imageId').attr('src', imagefile);
/* Image Upload Start */
var ft = new FileTransfer();
var options = new FileUploadOptions();
options.fileKey="vImage1";
options.fileName=imagefile.substr(imagefile.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
ft.upload(imagefile, your_service_url, win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
//alert($.parseJSON(r.response))
}
function fail(error) {
console.log("Response = " + error.code);
}

You may use HTML5 which has brought a surge of access to device hardware.
See this Link Capturing Audio & Video in HTML5
Note :getUserMedia() has been supported since Chrome 21, Opera 18, and Firefox 17.
Please go through support browser list (for mobile phone also) before implementing this.

Related

google drive picker and DriveApp is not defined error

This is my google drive file choose api code.
when I tried to run this code showing me error like DriveApp is not defined.
In this code I am getting error on that particular part:
function getOAuthToken() {
DriveApp.getRootFolder();
return ScriptApp.getOAuthToken();
}
I am referring the google documentation but still I am getting those error.
https://developers.google.com/picker/docs/
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<script>
// IMPORTANT: Replace the value for DEVELOPER_KEY with the API key obtained
// from the Google Developers Console.
var DEVELOPER_KEY = 'key';
var DIALOG_DIMENSIONS = {width: 600, height: 425};
var pickerApiLoaded = false;
function onApiLoad() {
gapi.load('picker', {'callback': function() {
pickerApiLoaded = true;
}});
}
function getOAuthToken() {
google.script.run.withSuccessHandler(createPicker)
.withFailureHandler(showError).getOAuthToken();
}
function createPicker(token) {
var uploadView = new google.picker.DocsUploadView().setIncludeFolders(true);
if (pickerApiLoaded && token) {
var picker = new google.picker.PickerBuilder()
// Instruct Picker to display only spreadsheets in Drive. For other
// views, see https://developers.google.com/picker/docs/#otherviews
.addView(uploadView)
.enableFeature(google.picker.Feature.NAV_HIDDEN)
.hideTitleBar()
.setOAuthToken(token)
.setDeveloperKey(DEVELOPER_KEY)
.setCallback(pickerCallback)
.setOrigin(google.script.host.origin)
.setSize(DIALOG_DIMENSIONS.width - 2,DIALOG_DIMENSIONS.height - 2)
.build();
picker.setVisible(true);
} else {
showError('Unable to load the file picker.');
}
}
function pickerCallback(data) {
var action = data[google.picker.Response.ACTION];
if (action == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
var id = doc[google.picker.Document.ID];
var url = doc[google.picker.Document.URL];
var title = doc[google.picker.Document.NAME];
document.getElementById('result').innerHTML =
'<b>You chose:</b><br>Name: <a href="' + url + '">' + title +
'</a><br>ID: ' + id;
} else if (action == google.picker.Action.CANCEL) {
document.getElementById('result').innerHTML = 'Picker canceled.';
}
}
function showError(message) {
document.getElementById('result').innerHTML = 'Error: ' + message;
}
</script>
</head>
<body>
<div>
<button onclick='getOAuthToken()'>Select a file</button>
<p id='result'></p>
</div>
<script src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
</body>
<script>
function showPicker() {
var html = HtmlService.createHtmlOutputFromFile('PickerHTML2.html')
.setWidth(600)
.setHeight(425)
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi().showModalDialog(html, 'Select a file');
}
function getOAuthToken() {
DriveApp.getRootFolder();
return ScriptApp.getOAuthToken();
}
</script>
</html>
When I try to run this code its showing error.
thank you in advance to everybody for any help or advice.

Client side Javascript get video width/height before upload

I've been trying to piece together a combination of HTML5 video tag + the FileReader API but I haven't figured out how to get the dimensions of a video that a user is providing from their own computer.
Here is what I am referencing for width/ height:
HTML5 Video Dimensions
<video id="foo" src="foo.mp4"></video>
var vid = document.getElementById("foo");
vid.videoHeight; // returns the intrinsic height of the video
vid.videoWidth; // returns the intrinsic width of the video
But I want to know if it's possible to do this with a file from a user's computer (that they have selected via a normal input html tag).
Thanks!
A bit unclean solution using basic FileReader + Data URL.
<html>
<head>
<style>
div {
margin: 20px;
}
</style>
</head>
<body>
<h1>Get Dimensions</h1>
<div>
<label for="load-file">Load a file:</label>
<input type="file" id="load-file">
</div>
<div>
<button type="button" id="done-button">Get me dimensions</button>
</div>
<script src="//cdn.jsdelivr.net/jquery/2.1.4/jquery.js"></script>
<script>
(function ($) {
$('#done-button').on('click', function () {
var file = $('#load-file')[0].files[0];
var reader = new FileReader();
var fileType = file.type;
console.log("type", fileType);
reader.addEventListener("load", function () {
var dataUrl = reader.result;
var videoId = "videoMain";
var $videoEl = $('<video id="' + videoId + '"></video>');
$("body").append($videoEl);
$videoEl.attr('src', dataUrl);
var videoTagRef = $videoEl[0];
videoTagRef.addEventListener('loadedmetadata', function(e){
console.log(videoTagRef.videoWidth, videoTagRef.videoHeight);
});
}, false);
if (file) {
reader.readAsDataURL(file);
}
});
})(jQuery);
</script>
</body>
</html>
Here is a simple and fast solution to get a video's size before upload.
It doesn't require any dependency.
const url = URL.createObjectURL(file);
const $video = document.createElement("video");
$video.src = url;
$video.addEventListener("loadedmetadata", function () {
console.log("width:", this.videoWidth);
console.log("height:", this.videoHeight);
});
const onSelectVideo = (files) => {
const file = files[0];
const url = URL.createObjectURL(file);
let videoId = "videoMain";
const video = document.createElement("video");
const body = document.getElementsByTagName("body");
video.setAttribute("src", url);
video.setAttribute("videoId", videoId);
body[0]?.append(video);
let videoTagRef = document.querySelector("[videoId='videoMain']");
videoTagRef.addEventListener("loadedmetadata", function (e) {
console.log(videoTagRef.videoWidth, videoTagRef.videoHeight);
});}

record audio from user and save to server

I'm trying to record audio from a website user and save the audio to my server. Many of the posts I have studied so far have referenced Matt Diamond's recorderjs. I attempted to recreate the demo at http://webaudiodemos.appspot.com/AudioRecorder/index.html by opening the source code through my browser. I copied the html, "audiodisplay.js", "recorder.js", and "main.js" and put them on my server. I also added the "recorderWorker.js" file from his GitHub site. In the recorder.js file, I changed var WORKER_PATH = 'js/recorderjs/recorderWorker.js' to var WORKER_PATH = 'recorderWorker.js';
When I run the demo I set up, I'm getting the "would you like to share your microphone.." warning and I can start the recording by pressing the mic icon on the right side. However, when I stop recording, the audio waveform doesn't show up below like in Matt's demo and the save icon doesn't become activated.
If I can get the demo up and running, the next problem I have is saving the wav file to the server instead of locally like in the demo. I've found several posts saying to use XMLHttpRequest(), however I can't really figure out how to connect those examples to recorderjs. Saving WAV File Recorded in Chrome to Server HTML5 & getUserMedia - Record Audio & Save to Web Server after Certain Time RecorderJS uploading recorded blob via AJAX
Using XMLHttpRequest to post wav or mp3 blobs to server is simple.
Just run this code wherever you have access to the blob element:
var xhr=new XMLHttpRequest();
xhr.onload=function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
var fd=new FormData();
fd.append("audio_data",blob, "filename");
xhr.open("POST","upload.php",true);
xhr.send(fd);
I prefer XMLHttpRequest to $.ajax() because it does not require jQuery.
Server-side, upload.php is as simple as:
$input = $_FILES['audio_data']['tmp_name']; //temporary name that PHP gave to the uploaded file
$output = $_FILES['audio_data']['name'].".wav"; //letting the client control the filename is a rather bad idea
//move the file from temp name to local folder using $output name
move_uploaded_file($input, $output)
Source: https://blog.addpipe.com/using-recorder-js-to-capture-wav-audio-in-your-html5-web-site/
Live demo: https://addpipe.com/simple-recorderjs-demo/
I figured out one solution, but would still welcome others related to recorderjs. I used MP3RecorderJS at https://github.com/icatcher-at/MP3RecorderJS. The demo html works if you change the top of the html from src="js/jquery.min.js" and src="js/mp3recorder.js" to wherever they're located in your server. For me, it is src="jquery.min.js" and src="mp3recorder.js" I also had to do the same thing to the "mp3recorder.js" file: var RECORDER_WORKER_PATH = 'js/recorderWorker.js'; var ENCODER_WORKER_PATH = 'js/mp3Worker.js'; changed to var RECORDER_WORKER_PATH = 'recorderWorker.js'; var ENCODER_WORKER_PATH = 'mp3Worker.js';
The program is set up to record both mp3 and wav. I wanted wav, so I made a few more adjustments to the html file. At line 55 you'll find:
recorderObject.exportMP3(function(base64_mp3_data) {
var url = 'data:audio/mp3;base64,' + base64_mp3_data;
var au = document.createElement('audio');
I changed that to:
recorderObject.exportWAV(function(base64_wav_data) {
var url = 'data:audio/wav;base64,' + base64_wav_data;
var au = document.createElement('audio');
The demo appends a new player each time you record. To prevent this, I deleted (commented out) the $recorder.append(au); part, made a new div to store the audio player, and then I clear that div each time, before the audio player is created. To upload to my server, I used a technique I learned from uploading images to a server save canvas image to server Basically, the "url" variable in line 56 was what I needed, but couldn't figure out how to put it in a universal variable to use by another function. So, I made a hidden div and made the contents of it equal to "url". I then referenced that div in a new function called "upload". I then used a php file called "uploadWav.php". I still have to figure out a way to activate and deactivate the upload button to prevent the user from uploading a blank file before recording, but that's another issue. Here's the final html and php that worked for me:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>MP3 Recorder test</title>
</head>
<body id="index" onload="">
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="mp3recorder.js"></script>
<script type="text/javascript">
var audio_context;
function __log(e, data) {
log.innerHTML += "\n" + e + " " + (data || '');
}
$(function() {
try {
// webkit shim
window.AudioContext = window.AudioContext || window.webkitAudioContext;
navigator.getUserMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
window.URL = window.URL || window.webkitURL;
var audio_context = new AudioContext;
__log('Audio context set up.');
__log('navigator.getUserMedia ' + (navigator.getUserMedia ? 'available.' : 'not present!'));
} catch (e) {
alert('No web audio support in this browser!');
}
$('.recorder .start').on('click', function() {
$this = $(this);
$recorder = $this.parent();
navigator.getUserMedia({audio: true}, function(stream) {
var recorderObject = new MP3Recorder(audio_context, stream, { statusContainer: $recorder.find('.status'), statusMethod: 'replace' });
$recorder.data('recorderObject', recorderObject);
recorderObject.start();
}, function(e) { });
});
$('.recorder .stop').on('click', function() {
$this = $(this);
$recorder = $this.parent();
recorderObject = $recorder.data('recorderObject');
recorderObject.stop();
recorderObject.exportWAV(function(base64_wav_data) {
var url = 'data:audio/wav;base64,' + base64_wav_data;
var au = document.createElement('audio');
document.getElementById("playerContainer").innerHTML = "";
//console.log(url)
var duc = document.getElementById("dataUrlcontainer");
duc.innerHTML = url;
au.controls = true;
au.src = url;
//$recorder.append(au);
$('#playerContainer').append(au);
recorderObject.logStatus('');
});
});
});
</script>
<script>
function upload(){
var dataURL = document.getElementById("dataUrlcontainer").innerHTML;
$.ajax({
type: "POST",
url: "uploadWav.php",
data: {
wavBase64: dataURL
}
}).done(function(o) {
console.log('saved');
});
}
</script>
<div class="recorder">
Recorder 1
<input type="button" class="start" value="Record" />
<input type="button" class="stop" value="Stop" />
<pre class="status"></pre>
</div>
<div><button onclick="upload()">Upload</button></div>
<div id="playerContainer"></div>
<div id="dataUrlcontainer" hidden></div>
<pre id="log"></pre>
</body>
</html>
and the "uploadWav.php" file:
<?php
// requires php5
define('UPLOAD_DIR', 'uploads/');
$img = $_POST['wavBase64'];
$img = str_replace('data:audio/wav;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.wav';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
//**Server Side Code**
package myPack;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
#WebServlet("/MyServlet")
#MultipartConfig
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public MyServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
String name = request.getParameter("fname");
String url = request.getParameter("myUrl");
url = url.replace("data:audio/wav;base64,", "");
url = url.replace(" ", "+");
byte[] bytes = url.getBytes();
byte[] valueDecoded = Base64.decodeBase64(bytes);
FileOutputStream os = new FileOutputStream(new File("D://" + name
+ ".wav"));
os.write(valueDecoded);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
**Client Side Code**
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>MP3 Recorder test</title>
</head>
<body id="index" onload="">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/recorder.js"></script>
<script type="text/javascript">
var audio_context;
function __log(e, data) {
log.innerHTML += "\n" + e + " " + (data || '');
}
$(function() {
try {
// webkit shim
window.AudioContext = window.AudioContext || window.webkitAudioContext;
navigator.getUserMedia = ( navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
window.URL = window.URL || window.webkitURL;
var audio_context = new AudioContext;
__log('Audio context set up.');
__log('navigator.getUserMedia ' + (navigator.getUserMedia ? 'available.' : 'not present!'));
} catch (e) {
alert('No web audio support in this browser!');
}
$('.recorder .start').on('click', function() {
$this = $(this);
$recorder = $this.parent();
navigator.getUserMedia({audio: true}, function(stream) {
var recorderObject = new MP3Recorder(audio_context, stream, { statusContainer: $recorder.find('.status'), statusMethod: 'replace' });
$recorder.data('recorderObject', recorderObject);
recorderObject.start();
}, function(e) { });
});
$('.recorder .stop').on('click', function() {
$this = $(this);
$recorder = $this.parent();
recorderObject = $recorder.data('recorderObject');
recorderObject.stop();
recorderObject.exportWAV(function(base64_wav_data) {
var url = 'data:audio/wav;base64,' + base64_wav_data;
var au = document.createElement('audio');
document.getElementById("playerContainer").innerHTML = "";
//console.log(url)
var duc = document.getElementById("dataUrlcontainer");
duc.innerHTML = url;
au.controls = true;
au.src = url;
//$recorder.append(au);
$('#playerContainer').append(au);
var fd = new FormData();
fd.append('fname', 'test.wav');
fd.append('myUrl', duc.innerHTML);
$.ajax({
type: "POST",
url: "/audioPart2/MyServlet",
data: fd,
processData: false,
contentType: false
});
recorderObject.logStatus('');
});
});
});
</script>
<div class="recorder">
Recorder 1 <input type="button" class="start" value="Record" /> <input
type="button" class="stop" value="Stop" />
<div id="playerContainer"></div>
<div id="dataUrlcontainer" hidden></div>
<pre class="status"></pre>
</div>
<!-- <div class="recorder"> -->
<!-- Recorder 2 <input type="button" class="start" value="Record" /> <input -->
<!-- type="button" class="stop" value="Stop" /> -->
<!-- <pre class="status"></pre> -->
<!-- </div> -->
<pre id="log"></pre>
</body>
</html>
**// Required JS
1)jquery.min.js
2) recorder.js**
**recorder.js is below**
(function(window){
var RECORDER_WORKER_PATH = 'js/recorderWorker.js';
var ENCODER_WORKER_PATH = 'js/mp3Worker.js';
var MP3Recorder = function(context, stream, cfg) {
var config = cfg || { statusContainer: null, statusMethod: 'append' }
var bufferLen = 4096;
var recording = false;
this.source = context.createMediaStreamSource(stream);
this.node = (context.createScriptProcessor || context.createJavaScriptNode).call(context, bufferLen, 1, 1);
var recorderWorker = new Worker(RECORDER_WORKER_PATH);
var encoderWorker = new Worker(ENCODER_WORKER_PATH);
var exportCallback;
// initialize the Recorder Worker
recorderWorker.postMessage({ cmd: 'init', sampleRate: context.sampleRate });
// the recording loop
this.node.onaudioprocess = function(e) {
if(!recording) return;
recorderWorker.postMessage({ cmd: 'record', buffer: e.inputBuffer.getChannelData(0) });
}
this.start = function() {
recording = true;
this.logStatus('recording...');
}
this.stop = function() {
recording = false;
this.logStatus('stopping...');
}
this.destroy = function() { recorderWorker.postMessage({ cmd: 'destroy' }); }
this.logStatus = function(status) {
if(config.statusContainer) {
if(config.statusMethod == 'append') {
config.statusContainer.text(config.statusContainer.text + "\n" + status);
} else {
config.statusContainer.text(status);
}
}
}
this.exportBlob = function(cb) {
exportCallback = cb;
if (!exportCallback) throw new Error('Callback not set');
recorderWorker.postMessage({ cmd: 'exportBlob' });
}
this.exportWAV = function(cb) {
// export the blob from the worker
this.exportBlob(function(blob) {
var fileReader = new FileReader();
// read the blob as array buffer and convert it
// to a base64 encoded WAV buffer
fileReader.addEventListener("loadend", function() {
var resultBuffer = new Uint8Array(this.result);
cb(encode64(resultBuffer));
});
fileReader.readAsArrayBuffer(blob);
});
}
this.exportMP3 = function(cb) {
this.logStatus('converting...');
// export the blob from the worker
this.exportBlob(function(blob) {
var fileReader = new FileReader();
fileReader.addEventListener("loadend", function() {
var wavBuffer = new Uint8Array(this.result);
var wavData = parseWav(wavBuffer);
encoderWorker.addEventListener('message', function(e) {
if (e.data.cmd == 'data') {
cb(encode64(e.data.buffer));
}
});
encoderWorker.postMessage({ cmd: 'init', config: { mode: 3, channels: 1, samplerate: wavData.sampleRate, bitrate: wavData.bitsPerSample } });
encoderWorker.postMessage({ cmd: 'encode', buf: Uint8ArrayToFloat32Array(wavData.samples) });
encoderWorker.postMessage({ cmd: 'finish' });
});
fileReader.readAsArrayBuffer(blob);
});
}
// event listener for return values of the recorderWorker
recorderWorker.addEventListener('message', function(e) {
switch(e.data.from) {
case 'exportBlob':
exportCallback(e.data.blob);
break;
};
});
// HELPER FUNCTIONS
function encode64(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for(var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
function parseWav(wav) {
function readInt(i, bytes) {
var ret = 0, shft = 0;
while(bytes) {
ret += wav[i] << shft; shft += 8;
i++; bytes--;
}
return ret;
}
if(readInt(20, 2) != 1) throw 'Invalid compression code, not PCM';
if(readInt(22, 2) != 1) throw 'Invalid number of channels, not 1';
return { sampleRate: readInt(24, 4), bitsPerSample: readInt(34, 2), samples: wav.subarray(44) };
}
function Uint8ArrayToFloat32Array(u8a){
var f32Buffer = new Float32Array(u8a.length);
for (var i = 0; i < u8a.length; i++) {
var value = u8a[i<<1] + (u8a[(i<<1)+1]<<8);
if (value >= 0x8000) value |= ~0x7FFF;
f32Buffer[i] = value / 0x8000;
}
return f32Buffer;
}
this.source.connect(this.node);
this.node.connect(context.destination); // this should not be necessary
}
window.MP3Recorder = MP3Recorder;
})(window);

Upload an image with Phonegap: InvalidCastException

I am trying to upload a file to my server with Phonegap. I am currently stuck when an error that says:
InvalidCastException
Failed to deserialize WP7CordovaClassLib.Cordova.Commands.FileTransfer+UploadOptions[] with JSON value :: ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://server.myapp.srv.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]
The HTML + Javascript
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<title>File Transfer Example</title>
</head>
<body>
<button id="uploadPhotoButton">Upload a Photo</button>
<script type="text/javascript" src="cordova-2.2.0.js"></script>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript" src="js/camera.js"></script>
<script type="text/javascript">
$(document).one("pause", function () {
console.log('Paused.');
});
$(document).one("resume", function () {
console.log('Resumed.');
});
$(document).one("deviceready", function () {
console.log('Device is ready.');
});
$(document).one("backbutton", function () {
console.log('Back button pressed.');
});
$(document).ready(function () {
console.log('DOM is ready.');
$(document).on("click", "#uploadPhotoButton", function (e) {
console.log('clicked button');
getImage();
});
function getImage() {
// Retrieve image file location from specified source
navigator.camera.getPicture(uploadPhoto, function (message) {
alert('get picture failed');
}, {
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://my.server.co.nz/pages/fileupload", win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error) {
alert("An error has occurred: Code = " = error.code);
}
});
</script>
</body>
</html>
The complete error log.
GapBrowser_Navigated :: /app/www/index.html#/app/www/uploadtest.html
Log:"clicked button"
The thread '<No Name>' (0xf55026a) has exited with code 0 (0x0).
The thread '<No Name>' (0xe3f0326) has exited with code 0 (0x0).
INFO: AppDeactivated
INFO: AppActivated
Log:"Paused."
The thread '<No Name>' (0xf1a02e6) has exited with code 0 (0x0).
Log:"Resumed."
The thread '<No Name>' (0xf2a01d2) has exited with code 0 (0x0).
options = ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://my.server.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]
A first chance exception of type 'System.InvalidCastException' occurred in System.ServiceModel.Web.dll
A first chance exception of type 'System.InvalidCastException' occurred in System.ServiceModel.Web.dll
InvalidCastException
Failed to deserialize WP7CordovaClassLib.Cordova.Commands.FileTransfer+UploadOptions[] with JSON value :: ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://server.myapp.srv.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]
A first chance exception of type 'System.NullReferenceException' occurred in Lion.MyApp.dll
The thread '<No Name>' (0xfdc025e) has exited with code 0 (0x0).
Log:"Error in error callback: FileTransfer1325332352 = ReferenceError: Invalid left-hand side in assignment"
The thread '<No Name>' (0xfa60286) has exited with code 0 (0x0).
Does anyone have an idea on how to make this work?
Thanks!
W
I'm thinking that you are malforming your options value. Do you need to pass JSON or an actual object?
Right now you are passing an array with text in it.
options = ["{\"filePath\":\"/CapturedImagesCache/PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"server\":\"http://my.server.co.nz/pages/fileupload\",\"fileKey\":\"file\",\"fileName\":\"PhotoChooser-51766419-c657-46db-a53d-f09bee300a89.jpg\",\"mimeType\":\"image/jpg\",\"params\":\"value1=test&value2=param\",\"chunkedMode\":false}"]
The error seems to involve deserialization issues.
Put your getImage, uploadImage, win, fail outside of $(document).ready 's inline function call.
Reference to win and fail are actually closure, and phone gap gets it as null when it is trying to access those methods directly. Phonegap is probably expecting a global function instead of hidden function inside a function.
PhoneGap's executes its code out side javascript context, what may work in true javascript fashion may not work correctly with phonegap.
I had a problem similar to yours. I solved this, changing mimeType parameter to 'text/plain'.
Do you use params to send? If it's false I think you need send empty params.
I had this problem before, try to prepare the image in the html first, and dont take it directly from the navigator, it may not saving the taken photo in it cash ;)
In my solution I suppose to have an image tage with id ='camera_image'
img id='camera_image'...
Then i set all the variables of the image in it and I upload it (as you will see in the following code).
here's the 2 functions i used:
function takephoto(){
navigator.camera.getPicture(
function(uri){
$('#camera_image').show();
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
uploadPhoto(img);
alert("Success");
},
function(e) {
console.log("Error getting picture: " + e);
},
{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI
});
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
alert("Take picture or select picture from library first.");
return;
}
}
for choosing an existing photo:
function choosephoto(){
navigator.camera.getPicture(
function(uri) {
$('#camera_image').show();
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
uploadPhoto(img);
},
function(e) {
console.log("Error getting picture: " + e);
},
{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.SAVEDPHOTOALBUM
});
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
alert("please select a pic first");
return;
}
}
in the upload function:
function uploadPhoto(img) {
imageURI = img.src ...
ps: sorry for the formatting of my code, it doesn't fix well.

upload images or videos to remote server using phonegap

I am doing project in android phonegap.Here I want to upload images and videos to remote server.
I used the following link.
http://zacvineyard.com/blog/2011/03/upload-a-file-to-a-remote-server-with-phonegap
I also change some options like options.chunkedMode = false ,android:debuggable="true" and
. But still it shows error code 3.I am using the cordova-2.0.0.js version.Can anyone suggest some answer.
My js code is
**
<script type="text/javascript" charset="utf-8">
// Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
function onDeviceReady() {
// Do cool things here...
}
function getImage() {
// Retrieve image file location from specified source
navigator.camera.getPicture(uploadPhoto, function(message) {
alert('get picture failed');
},
{quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);
}
function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "url of ther server/upload.php", win, fail, options, true);
console.log("H");
}
function win(r) {
console.log("HIIIIIiiii");
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error) {
alert("There is something");
alert("An error has occurred: Code = " + error.code);
}
</script>
**
and my php code is
<?php
print_r($_FILES);
$new_image_name = "namethisimage.jpg";
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$new_image_name);
?>
Thanks.
Have you added the URL in question to your whitelist?
e.g. in config.xml do you have something like:
<access origin="www.myurl.com" subdomains="true" />
or
<access origin="*" />
which allows all URLs.
Error code 3 is a FileTransferError.CONNECTION_ERR by the way.

Categories

Resources