Redirect after file upload in phonegap - javascript

My phonegap upload script works perfectly. After the upload you get a message "Please wait redirecting". I want to know how to add a redirection script so immediately after upload, it redirects to another page
var deviceReady = false;
/**
* Take picture with camera
*/
function takePicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI});
};
/**
* Select picture from library
*/
function selectPicture() {
navigator.camera.getPicture(
function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
},
function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
},
{ quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
};
/**
* Upload current picture
*/
function uploadPicture() {
// Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
document.getElementById('camera_status').innerHTML = "Take picture or select picture from library first.";
return;
}
// Verify server has been entered
server = document.getElementById('serverUrl').value;
if (server) {
// Specify transfer options
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1)+'.jpg';
options.mimeType="image/jpeg";
options.chunkedMode = false;
options.params = {
filename: window.localStorage.setItem("key", options.fileName)
}
// Transfer picture to server
var ft = new FileTransfer();
ft.upload(imageURI, "http://myphonegap.com/upload.php", function(r) {
document.getElementById('camera_status').innerHTML = "Please wait redirecting";
}, function(error) {
document.getElementById('camera_status').innerHTML = "Upload failed: Code = "+error.code;
}, options);
}
}
/**
* View pictures uploaded to the server
*/
function viewUploadedPictures() {
// Get server URL
server = document.getElementById('serverUrl').value;
if (server) {
// Get HTML that lists all pictures on server using XHR
var xmlhttp = new XMLHttpRequest();
// Callback function when XMLHttpRequest is ready
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState === 4){
// HTML is returned, which has pictures to display
if (xmlhttp.status === 200) {
document.getElementById('server_images').innerHTML = xmlhttp.responseText;
}
// If error
else {
document.getElementById('server_images').innerHTML = "Error retrieving pictures from server.";
}
}
};
xmlhttp.open("GET", server , true);
xmlhttp.send();
}
}
/**
* Function called when page has finished loading.
*/
function init() {
document.addEventListener("deviceready", function() {deviceReady = true;}, false);
window.setTimeout(function() {
if (!deviceReady) {
alert("Error: PhoneGap did not initialize. Demo will not run correctly.");
}
},2000);
}

Just do the page transition at the end of the success function. E.g after This line:
document.getElementById('camera_status').innerHTML = "Please wait redirecting";
Do:
window.location.href = "otherpage.html"
Or:
$('page1_div').hide();
$('page2_div').show();
Etc.

Related

How to overcome a post 405 error on windows 2012 R2 server

I have a small test application to record the camera and sent the file to a directory on my server.
The main file is as follow:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.WebRTC-Experiment.com/RecordRTC.js"></script>
<style>
video {
max-width: 100%;
border: 5px solid yellow;
border-radius: 9px;
}
body {
background: black;
}
h1 {
color: yellow;
}
</style>
</head>
<body>
<h1 id="header">RecordRTC Upload to PHP</h1>
<video id="your-video-id" controls="" autoplay=""></video>
<script type="text/javascript">
// capture camera and/or microphone
navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(function(camera) {
// preview camera during recording
document.getElementById('your-video-id').muted = true;
document.getElementById('your-video-id').srcObject = camera;
// recording configuration/hints/parameters
var recordingHints = {
type: 'video'
};
// initiating the recorder
var recorder = RecordRTC(camera, recordingHints);
// starting recording here
recorder.startRecording();
// auto stop recording after 5 seconds
var milliSeconds = 5 * 1000;
setTimeout(function() {
// stop recording
recorder.stopRecording(function() {
// get recorded blob
var blob = recorder.getBlob();
// generating a random file name
var fileName = getFileName('webm');
// we need to upload "File" --- not "Blob"
var fileObject = new File([blob], fileName, {
type: 'video/webm'
});
uploadToPHPServer(fileObject, function(response, fileDownloadURL) {
if(response !== 'ended') {
document.getElementById('header').innerHTML = response; // upload progress
return;
}
document.getElementById('header').innerHTML = '' + fileDownloadURL + '';
alert('Successfully uploaded recorded blob.');
// preview uploaded file
document.getElementById('your-video-id').src = fileDownloadURL;
// open uploaded file in a new tab
window.open(fileDownloadURL);
});
// release camera
document.getElementById('your-video-id').srcObject = null;
camera.getTracks().forEach(function(track) {
track.stop();
});
});
}, milliSeconds);
});
function uploadToPHPServer(blob, callback) {
// create FormData
var formData = new FormData();
formData.append('video-filename', blob.name);
console.log("blob.name:");
console.log(blob.name);
formData.append('video-blob', blob);
callback('Uploading recorded-file to server.');
makeXMLHttpRequest('https://xxx/yyy/', formData, function(progress) {
if (progress !== 'upload-ended') {
callback(progress);
return;
}
var initialURL = 'https://xxx/yyy/' + blob.name;
callback('ended', initialURL);
});
}
function makeXMLHttpRequest(url, data, callback) {
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
if (request.responseText === 'success') {
callback('upload-ended');
return;
}
alert(request.responseText);
return;
}
};
request.upload.onloadstart = function() {
callback('PHP upload started...');
};
request.upload.onprogress = function(event) {
callback('PHP upload Progress ' + Math.round(event.loaded / event.total * 100) + "%");
};
request.upload.onload = function() {
callback('progress-about-to-end');
};
request.upload.onload = function() {
callback('PHP upload ended. Getting file URL.');
};
request.upload.onerror = function(error) {
callback('PHP upload failed.');
};
request.upload.onabort = function(error) {
callback('PHP upload aborted.');
};
request.open('POST', url);
request.send(data);
}
// this function is used to generate random file name
function getFileName(fileExtension) {
var d = new Date();
var year = d.getUTCFullYear();
var month = d.getUTCMonth();
var date = d.getUTCDate();
return 'RecordRTC-' + year + month + date + '-' + getRandomString() + '.' + fileExtension;
}
function getRandomString() {
if (window.crypto && window.crypto.getRandomValues && navigator.userAgent.indexOf('Safari') === -1) {
var a = window.crypto.getRandomValues(new Uint32Array(3)),
token = '';
for (var i = 0, l = a.length; i < l; i++) {
token += a[i].toString(36);
}
return token;
} else {
return (Math.random() * new Date().getTime()).toString(36).replace(/\./g, '');
}
}
</script>
</body>
</html>
in the location where the files are stored I have the following file
<?php
// path to ~/tmp directory
$tempName = $_FILES['video-blob']['tmp_name'];
// move file from ~/tmp to "uploads" directory
if (!move_uploaded_file($tempName, $filePath)) {
// failure report
echo getcwd();
echo " | ";
echo 'Problem saving file: '.$tempName .' to ' .$filePath .' Not uploaded because of error #'.$_FILES['video-blob']['error'];
if (!is_writable($filePath)) {
echo " | ";
echo "dir not writable or existing";
}
die();
}
// success report
echo 'success';
?>
When I run this on my local server it works fine. But when I upload it to my windows 2012 R2 server I get the error
POST https://xxx/yyy/ 405 (Method Not Allowed)
I tried to play with the handler mappings in ISS and disabled WebDAV but no luck.
Since it works on the localhost but not on the windows server I figure it must be something related with the IIS setting but can not find out what.
Any help is appreciated.
In the end I found the error myself.
The settings in the web.config file where not standing correctly for FastCgiModule / StaticFileModules.

Chrome crashes when use XHR to send large file

I use XMLHttpRequest to send POST data to nodejs (expressjs api). The size of file about 200mb. When I do, Chrome crashes, but the Firefox doesn't. Does Chrome have a limited file size?
And how can I upload the large file via JavaScript?
This is my code send xhr request:
// create http request API AI Engine
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.responseType = 'arraybuffer';
xhr.timeout = 3600000;
xhr.onload = function() {
// reponse measage
if (this.status === 200) {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'none';
zip.files = {};
// unzip File
zip.loadAsync(this.response)
.then(function(zip) {
// will be called, even if content is corrupted
for (const file in zip.files) {
if (zip.files.hasOwnProperty(file)) {
const fileObject = zip.files[file];
fileObject.async('arraybuffer').then(function(fileData) {
var fileSave = new Blob([new Uint8Array(
fileData)]);
// Save file
saveAs(fileSave, fileObject.name);
})
}
}
}, function(e) {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not unzip file return.';
});
// get response stream data
} else {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not analyze file: ' + this.statusText;
}
};
// Handle when have error with xhr, show message
xhr.onerror = function(err) {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not analyze file: ' + this.statusText;
};
// Handle when have timeout with xhr, show message
xhr.ontimeout = function() {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not analyze file: Request time out';
};
// Add custom header
xhr.setRequestHeader('Content-type', 'application/octet-stream');
xhr.setRequestHeader('file-name', Date.now().toString() + '.zip');
xhr.setRequestHeader('file-length', data.byteLength);
// Send arraybuffer to server
xhr.send(data);
});

File upload button is still not working in Cordova / Phonegap Project

Iam unable to upload pictures to a webserver with PHP backend.
My cordova camera script is able to taking the picture and show the picture in small size. But it is not able to upload an image. I dont no why. I call the function photoUpload(); and set the a onClick-event in the button like
<button class="camera-control" onclick="photoUpload();">UPLOAD</button>
Here is my JavaScript, whats wrong with it?
var pictureSource;
var destinationType;
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
function clearCache() {
navigator.camera.cleanup();
}
var retries = 0;
function onCapturePhoto(fileURI) {
$("#cameraPic").attr("src", fileURI);
var win = function (r) {
clearCache();
retries = 0;
navigator.notification.alert(
'',
onCapturePhoto,
'Der Upload wurde abgeschlossen',
'OK');
console.log(r);
}
var fail = function (error) {
navigator.notification.alert(
'Bitte versuchen Sie es noch einmal.',
onCapturePhoto,
'Ein unerwarteter Fehler ist aufgetreten',
'OK');
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
if (retries == 0) {
retries ++
setTimeout(function() {
onCapturePhoto(fileURI)
}, 1000)
} else {
retries = 0;
clearCache();
alert('Fehler!');
}
}
function photoUpload() {
var fileURI = $("#cameraPic").attr("src");
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
var params = new Object();
params.fileKey = "file";
options.params = {}; // eig = params, if we need to send parameters to the server request
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://xxxx/app/upload.php"), win, fail, options);
}
}
function capturePhoto() {
navigator.camera.getPicture(onCapturePhoto, onFail, {
quality: 50,
destinationType: destinationType.FILE_URI
});
}
function getPhoto(source) {
navigator.camera.getPicture(onPhotoURISuccess, onFail, {
quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
function onFail(message) {
alert('Failed because: ' + message);
}
Look your function photoUpload is located in the function onCapturePhoto! you need to move function photoUpload on the top level.
window.photoUpload = function() {
var fileURI = $("#cameraPic").attr("src");
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
var params = new Object();
params.fileKey = "file";
options.params = {}; // eig = params, if we need to send parameters to the server request
var ft = new FileTransfer();
ft.upload(fileURI, encodeURI("http://xxxx/app/upload.php"), win, fail, options);
}
And the better way to do it like:
<button class="camera-control" id="photoUploadButton;">UPLOAD</button>
document.getElementById("photoUploadButton").addEventListener("click", photoUpload);

building a voice recorder using html5 and javascript

I want to build a voice recorder using HTML5 same as one found in gitHub JSSoundecorder, but what I want is for the user to be able to choose the file format before recording the voice.I can do this using ffmpeg. In other words the user must be able to select the audio format by check box (mp3,wma,pcm) and in the background code, the .wav file usually created by the program instead of displaying it, it should be converted by the format selected then displayed in the new format.this is the ffmpeg code we can use ,but I don't know how to get the .wav audio file to convert it and show it.please if someone have ideas,or if can find demos I have been looking for weeks.this is the ffmpeg code:
var fileName;
var fileBuffer;
function timeToSeconds(time) {
var parts = time.split(":");
return parseFloat(parts[0]) * 60 * 60 + parseFloat(parts[1]) * 60 + parseFloat(parts[2]) + parseFloat("0." + parts[3]);
}
// create ffmpeg worker
function getFFMPEGWorker() {
// regexps for extracting time from ffmpeg logs
var durationRegexp = /Duration: (.*?), /
var timeRegexp = /time=(.*?) /;
var duration;
var ffmpegWorker = new Worker('worker.js');
var durationLine;
ffmpegWorker.addEventListener('message', function(event) {
var message = event.data;
console.log(message.type);
if (message.type === "ready" && window.File && window.FileList && window.FileReader) {
// script loaded, hide loader
$('#loading').hide();
} else if (message.type == "stdout") {
console.log(message.data);
} else if (message.type == "stderr") {
console.log(message.data);
// try to extract duration
if (durationRegexp.exec(message.data)) {
duration = timeToSeconds(durationRegexp.exec(message.data)[1]);
}
// try to extract time
if (timeRegexp.exec(message.data)) {
var time = timeToSeconds(timeRegexp.exec(message.data)[1]);
if (duration) {
$("#progress").text("Progress: " + Math.floor(time / duration * 100) + "%");
$("#progress").show();
}
}
} else if (message.type == "done") {
var code = message.data.code;
console.log(message.data);
var outFileNames = Object.keys(message.data.outputFiles);
console.log(outFileNames);
if (code == 0 && outFileNames.length) {
var outFileName = outFileNames[0];
var outFileBuffer = message.data.outputFiles[outFileName];
var src = window.URL.createObjectURL(new Blob([outFileBuffer]));
$("#downloadLink").attr('href', src);
$("#download").show();
} else {
$("#error").show();
}
$("#converting").hide();
$("#progress").hide();
}
}, false);
return ffmpegWorker;
}
// create ffmpeg worker
var ffmpegWorker = getFFMPEGWorker();
var ffmpegRunning = false;
$('#convert').click(function() {
// terminate existing worker
if (ffmpegRunning) {
ffmpegWorker.terminate();
ffmpegWorker = getFFMPEGWorker();
}
ffmpegRunning = true;
// display converting animation
$("#converting").show();
$("#error").hide();
// hide download div
$("#download").hide();
// change download file name
var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
var outFileName = fileName.substr(0, fileName.lastIndexOf('.')) + "." + getOutFormat();
$("#downloadLink").attr("download", outFileName);
$("#downloadLink").text(outFileName);
var arguments = [];
arguments.push("-i");
arguments.push(fileName);
arguments.push("-b:a");
arguments.push(getBitrate());
switch (getOutFormat()) {
case "mp3":
arguments.push("-acodec");
arguments.push("libmp3lame");
arguments.push("out.mp3");
break;
case "wma":
arguments.push("-acodec");
arguments.push("wmav1");
arguments.push("out.asf");
break;
case "pcm":
arguments.push("-f");
arguments.push("s16le");
arguments.push("-acodec");
arguments.push("pcm_s16le");
arguments.push("out.pcm");
}
ffmpegWorker.postMessage({
type: "command",
arguments: arguments,
files: [
{
"name": fileName,
"buffer": fileBuffer
}
]
});
});
function getOutFormat() {
return $('input[name=format]:checked').val();
}
function getBitrate() {
return $('input[name=bitrate]:checked').val();
}
// disable conversion at start
$('#convert').attr('disabled', 'true');
function readInputFile(file) {
// disable conversion for the time of file loading
$('#convert').attr('disabled', 'true');
// load file content
var reader = new FileReader();
reader.onload = function(e) {
$('#convert').removeAttr('disabled');
fileName = file.name;
console.log(fileName);
fileBuffer = e.target.result;
}
reader.readAsArrayBuffer(file);
}
// reset file selector at start
function resetInputFile() {
$("#inFile").wrap('<form>').closest('form').get(0).reset();
$("#inFile").unwrap();
}
resetInputFile();
function handleFileSelect(event) {
var files = event.target.files; // FileList object
console.log(files);
// files is a FileList of File objects. display first file name
file = files[0];
console.log(file);
if (file) {
$("#drop").text("Drop file here");
readInputFile(file);
}
}
// setup input file listeners
document.getElementById('inFile').addEventListener('change', handleFileSelect, false);

Image not uploaded using cordova file transfer android

I created a page to take an image or select an image from phone gallery and works normally, but i want to upload this photo selected to my server on Godaddy.
I used Cordova file transfer to upload, install file transfer by command line :
cordova plugin add https://github.com/apache/cordova-plugin-file-transfer.git
and I put a small code to upload this photo but no message alert(No error and no Success).
the code to select an image:
function onPhotoURISuccess(imageURI) {
// Uncomment to view the image file URI
// console.log(imageURI);
// Get image handle
//
var largeImage = document.getElementById('largeImage');
// Unhide image elements
//
largeImage.style.display = 'block';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
largeImage.src = imageURI;
upload();
}
Code Upload function:
function upload() {
alert('large');
var uploadingImage = document.getElementById('largeImage');
var imgUrl = uploadingImage.src;
window.resolveLocalFileSystemURI(imgUrl, resolveOnSuccess, fsFail);
options = new FileUploadOptions();
// parameter name of file:
options.fileKey = "my_image";
// name of the file:
options.fileName = imgUrl.substr(imgUrl.lastIndexOf('/') + 1);
// mime type:
options.mimeType = "image/jpeg";
params = {val1: "some value", val2: "some other value"};
options.params = params;
ft = new FileTransfer();
ft.upload(fileuri, "http://siencelb.org/raycoding/insurance/avatar", success, fail, options);
}
function resolveOnSuccess(entry) {
fileuri = entry.toURL();
//use fileuri to upload image on server
}
function fsFail(message) {
alert("Error Message: " + message + "Error Code:" + message.target.error.code);
}
I have two buttons first to select an image and put it into div largeImage and this works.
second button to upload this image selected
Note: the alert('large') is displayed.
I solve my Error and I want to publish it
function takePicture() {
navigator.camera.getPicture(function(uri) {
var img = document.getElementById('camera_image');
img.style.visibility = "visible";
img.style.display = "block";
img.src = uri;
document.getElementById('camera_status').innerHTML = "Success";
}, function(e) {
console.log("Error getting picture: " + e);
document.getElementById('camera_status').innerHTML = "Error getting picture.";
}, {quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI});
}
;
/** * Select picture from library */
function selectPicture() {
navigator.camera.getPicture({quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
}
;
function uploadPicture() { // Get URI of picture to upload
var img = document.getElementById('camera_image');
var imageURI = img.src;
if (!imageURI || (img.style.display == "none")) {
document.getElementById('camera_status').innerHTML = "Take picture or select picture from library first.";
return;
} // Verify server has been entered
server = "upload.php";
if (server) { // Specify transfer options
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
options.chunkedMode = false; // Transfer picture to server
var ft = new FileTransfer();
ft.upload(imageURI, server, function(r) {
document.getElementById('camera_status').innerHTML = "Upload successful: " + r.bytesSent + " bytes uploaded.";
}, function(error) {
document.getElementById('camera_status').innerHTML = "Upload failed: Code = " + error.code;
}, options);
}
}
the PHP code of upload.php
<?php
// Directory where uploaded images are saved
$dirname = "/avatar/";
// If uploading file
if ($_FILES) {
print_r($_FILES);
mkdir ($dirname, 0777, true);
move_uploaded_file($_FILES["file"]["tmp_name"],$dirname."/".$_FILES["file"]["name"]);}
?>

Categories