Image not uploaded using cordova file transfer android - javascript

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"]);}
?>

Related

Phonegap: FileTransferError.FILE_NOT_FOUND_ERR

I'm using the Phonegap file transfer plugin to upload a picture to the server. However I am getting error code: 1 (FileTransferError.FILE_NOT_FOUND_ERR). I've tested my server code with POSTMAN and I can upload and image successfully. However I get that error with the plugin. This is my code. The file is declared from "camera_image.src" and I can see the image when I append this to the src of an image on the fly. Any contributions? How is this code not perfect?
var fileURL = camera_image.src;
alert(fileURL);
var win = function (r) {
temp.push(r.response);
statusDom.innerHTML = "Upload Succesful!";
}
var fail = function (error) {
alert("An error has occurred: Code = " + error.code + " | Source:" + error.source + " | Target:" + error.target );
statusDom.innerHTML = "Upload failed!";
}
var options = new FileUploadOptions();
options.fileKey = "properties_photo";
options.fileName=fileURL.substr(fileURL.lastIndexOf('/') + 1);
options.headers = {
Connection: "close"
};
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
statusDom = document.querySelector('#status');
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
var perc = Math.floor(progressEvent.loaded / progressEvent.total * 100);
statusDom.innerHTML = perc + "% uploaded...";
console.log(perc);
} else {
if(statusDom.innerHTML == "") {
statusDom.innerHTML = "Loading";
} else {
statusDom.innerHTML += ".";
}
}
};
ft.upload(fileURL, encodeURI("http://cloud10.me/clients/itsonshow/app/image_upload_process.php"), win, fail, options);
I had this problem because of spaces in the path or filename of the file to be uploaded.
You need to ensure the plugin isn't being passed a fileURL with %20 in the URL.

camera photo uploaded as a File filetype with phongeap file transfer API

I'm uploading a photo taken by camera to server using file transfer API, however it's uploaded as a File filetype and the name of the photo is without the jpeg extension. The file can still be read as a image when I download, but I need to transfer the photo from the server to other API using the photo url, and the API expects to see the photo in the image filetype.
The javascript code to upload the photo:
var imgFilename = "";
//upload photo
function uploadPhoto(imageURI) {
//upload image
var fileName=imageURI.substr(imageURI.lastIndexOf('/') + 1);
//var uri = encodeURI('http://server...');
var options = new FileUploadOptions();
options.fileKey = "file";
if(fileName.indexOf('?')==-1){
options.fileName = fileName;
}else{
options.fileName = fileName.substr(0,fileName.indexOf('?'));
}
options.mimeType = "image/jpeg";//文件格式,默认为image/jpeg
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
options.headers = {Connection: "close"};
var ft = new FileTransfer();
ft.upload(imageURI, serverURL() + "/upload.php", win, fail, options);
}
function win(r){
if (imgFilename != ""){
deleteOldImg(imgFilename);
}
var arr = JSON.parse(r.response);
imgFilename = arr[0].result;
alert(r.response);
}
PHP code:
<?php
try{
$filename = tempnam('images', '');
$new_image_name = basename(preg_replace('"\.tmp$"', '.jpg', $filename));
unlink($filename);
//print_r($_FILES);
move_uploaded_file($_FILES["file"]["tmp_name"], "image/user-photo/2/" . $new_image_name);
$json_out = "[" . json_encode(array("result"=>$new_image_name)) . "]";
echo $json_out;
}
catch(Exception $e) {
$json_out = "[".json_encode(array("result"=>0))."]";
echo $json_out;
}
?>
The error code happens when PHP code is move_uploaded_file($_FILES["file"]["tmp_name"], 'image/user-photo/2/');

Redirect after file upload in phonegap

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.

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);

How To Upload Multiple Files To Server Using Javascript

I am using PhoneGap, and uploading a file (using a HTTP POST) like this,
function uploadSingleFile()
{
var ft = new FileTransfer();
// set up parameters etc
ft.upload(imageName, "http://serviceaddress/UploadFile.ashx", win, fail, options);
}
function win(r)
{
// success callback
}
I am wanting to upload muliple files, so in the success callback I want to call the uploadSingleFile to move onto the next file.
How can I store which file I am up to? I am using the localStorage to store the file names. So I would want to do this,
upload file localStorage.file0
upload file localStorage.file1
upload file localStorage.file2
So all I would need to do would be to store the number on the end, 0, 1, etc of where we are up to. Do I need to use a global variable? Seems messy.
If only I could pass through to the success callback a number as a additional parameter?
Hmmm. Is the problem worth doubting? Just store an array of file names and use JSON.stringify / JSON.parse for conversion between array and string.
function uploadSingleFile(fileName) {
var ft = new FileTransfer();
ft.upload("fileUrl",
"server",
function (result , fileName) {
console.log(fileName + ' has been uploaded successfully to server');
},
function (error) {
console.log(error);
},
{fileName: fileName, fileKey: "file"});
}
function uploadFiles() {
var files = JSON.parse(localStorage.files);
for(var i=0; i < files.length; i++) {
uploadSingleFile(files[i]);
}
}
You can send the index of file as parameter to uploadSingleFile() then using it in console.log()
First add all your images to array :
var TemplstImg = [];
function UploadImages()
{
var lstImages = [localStorage.file0,localStorage.file1,localStorage.file2];
TemplstImg=lstImages ;
if (TemplstImg.length > 0) {
var img = TemplstImg.pop();
uploadPhoto(img);
}
}
function uploadPhoto(imageURI) {
imageURI = imageURI.ImageFile;
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = {};
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload(imageURI, yourServerPath, winImg, failImg,options);
}
function winImg(r) {
if (TemplstImg.length == 0) {
alert ('Done , all files was uploaded');
} else {
var img = TemplstImg.pop();
uploadPhoto(img);
}
}
function failImg(error) {
alert("failImg An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}

Categories