Issues with uploading image to webserver using phonegap - javascript

EDIT: Changed win() function and added am image corresponding to it's result.
I am having trouble uploading image to a webserver using phonegap.
This is the code that I have for the app:
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for Cordova to connect with the device
//
document.addEventListener("deviceready",onDeviceReady,false);
// Cordova is ready to be used!
//
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
// Get image handle
//
var largeImage = document.getElementById('largeImage');
// Unhide image elements
//
largeImage.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
//
largeImage.src = 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://www.tayabsoomro.me/upload.php", 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 occured while uploading image: " + error.code);
}
The code triggers win() function and shows the JSON data of the result when the image is captured so at least it doesn't fail().
And here's an image of what win() function alerts.
and this is what my upload.php looks like:
<?php
print_r($_FILES);
$new_image_name = "myimg.jpg";
move_uploaded_file($_FILES["file"]["tmp_name"], "uploads/".$new_image_name);
?>

Ensure that you have all the appropriate (Read/Write) permissions set to your target folder uploads/ where you try to upload your files.
Hope this helps!.

Related

Cordova file transfer image is not uploading the file to server

Please help me to resolve this issue, am try to solve this from last week. Using cordova file transfer plugins am try to upload my image to production server
however am getting error code 1.
i checked source and target path both are accessible. Please find my cordova setup versions.
Cordova -> 7.1.0, Phonegap -> 7.1.1, cordova-plugin-file-transfer-> spec=1.7.1
Code:
function staticpathu_upload() {
var fileURL = 'https://example.com/Al_2_1518090802.jpg';
var uri = encodeURI('https://example.com/dummy.php');
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
var ft = new FileTransfer();
ft.upload(fileURL, uri, onSuccess, onError, options);
function onSuccess(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}
function onError(error) {
console.log(error);
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
}
Error:
FileTransferError {
code: 1,
source: "https://example.com/Al_2_1518090802.jpg",
target: "https://example.com/dummy.php",
http_status: null,
body: null,
}
This issue with ServerUrl, its not allowing me to post the image to server. I have created dummy.php on server root folder and execute from below code its working fine. It won't work from desktop we have check in mobiles or emulators only.
function uploadphoto(){
navigator.camera.getPicture(uponSuccess, uponFail, { quality: 50,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
allowEdit: true,
destinationType: Camera.DestinationType.FILE_URI
});
// Change image source and upload photo to server
function uponSuccess(imageURI) {
// Set image source
var image = document.getElementById('fileuploadimg');
$$('.gAlbumList').append('<img src="'+imageURI + '?' + Math.random()+'" />');
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;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "https://example.com/dummy.php", function(result){
$$('.error').append('<p>successfully uploaded ' + result.response+'</p>');
}, function(error){
$$('.error').append('<p>error : ' + JSON.stringify(error)+'</p>');
}, options);
}
function uponFail(message) {
$$('.error').append('<p>Failed because: ' + message+'</p>');
}
fileUrl must be a
Filesystem URL representing the file on the device or a data URI. For backwards compatibility, this can also be the full path of the file on the device. (See Backwards Compatibility Notes below)
See the docs
This is propably the reason why a FileTransferError.FILE_NOT_FOUND_ERR (error code 1) is thrown.

php get video from file_get_contents('php://input')

I'm trying to upload a video with some other parameters via a shared web worker.
Here below I paste de code I'm using:
record.js
function sendVideo(name, path) {
var worker = new SharedWorker("js/upload.js");
worker.port.postMessage([path, name + '.webm', blob]);
// worker.port.start();
worker.port.onmessage = function(e) {
console.log('Message received from worker ' + e.data);
}
}
upload.js
onconnect = function(e) {
var port = e.ports[0];
port.onmessage = function(e) {
var path = e.data[0];
var fileName = e.data[1];
var video = e.data[2];
var request = new XMLHttpRequest();
request.open('POST', 'http://localhost/channel/upload', true);
request.onload = function () {
port.postMessage(request.responseText);
};
request.send('fileName=' + fileName + '&video=' + video);
}
// port.start(); // not necessary since onmessage event handler is being used
}
channel.php
public function upload()
{
$data = file_get_contents('php://input');
// get the video from $data and move it
}
The problem is if my worker send:
request.send('fileName=' + fileName + '&video=' + video);
the content that my php code get is [blob data].
and if my worker send:
request.send('video=' + video);
the content that my php get is the video coded, full of special characters.
My question is how could I get the text and the video like if I had $_FILES in order to process it correctly.
Thanks in advice.

Prevent image file from loading to canvas after file size warning

I am trying to prevent the image file selected from loading to the canvas if it is larger than the maximum allowed I have set. The logic checks the image and throws a warning, but still loads the image being checked. How can I prevent this from occurring? Also, I need to be able to clear the image previously loaded, if a new one is loaded and checked. A newly loaded image that is too large, is not checked for validity or have a warning thrown if its too big.
var fileInput = document.getElementById("file"),
renderButton = $("#renderButton"),
submit = $(".submit"),
imgly = new ImglyKit({
container: "#container",
ratio: 1 / 1
});
// As soon as the user selects a file...
fileInput.addEventListener("change", function (event) {
//CHECK FILE SIZE OF INPUT
if (window.File && window.FileReader && window.FileList && window.Blob)
{
//get the file size and file type from file input field
var fsize = $('#file')[0].files[0].size;
var ftype = $('#file')[0].files[0].type;
var fname = $('#file')[0].files[0].name;
if(fsize>54000) //do something if file size more than 1 mb (1048576)
{
$(".file-warning").html("<div class='alert alert-danger'><p>The image: <b>" + fname +"</b> is <b>" + fsize/1000 + "KB</b> and too big!</p></div>");
//alert("Type :"+ ftype +" | "+ fsize +" bites\n(File: "+fname+") Too big!");
}
}else{
alert("Please upgrade your browser, because your current browser lacks some new features we need!");
}
//END FILE SIZE CHECK
var file;
var fileToBlob = event.target.files[0];
var blob = new Blob([fileToBlob], {
"type": fileToBlob.type
});
// do stuff with blob
console.log(blob);
// Find the selected file
if (event.target.files) {
file = event.target.files[0];
} else {
file = event.target.value;
}
// Use FileReader to turn the selected
// file into a data url. ImglyKit needs
// a data url or an image
var reader = new FileReader();
reader.onload = (function (file) {
return function (e) {
data = e.target.result;
// Run ImglyKit with the selected file
try {
imgly.run(data);
} catch (e) {
if (e.name == "NoSupportError") {
alert("Your browser does not support canvas.");
} else if (e.name == "InvalidError") {
alert("The given file is not an image");
}
}
};
})(file);
reader.readAsDataURL(file);
});
When file size check is failed - you should save wrong state (by changing to Boolean variable) or simply break execution of function:
if(fsize>54000) //do something if file size more than 1 mb (1048576)
{
$(".file-warning").html("<div class='alert alert-danger'><p>The image: <b>" + fname +"</b> is <b>" + fsize/1000 + "KB</b> and too big!</p></div>");
//alert("Type :"+ ftype +" | "+ fsize +" bites\n(File: "+fname+") Too big!");
isValidSize=false; // this variable should be created somewhere at the top. It will keep the state of file-picker.
return; //this will stop any further actions;
}

How to add image file in json using phonegap?

I have a problem saving an image in JSON. I can access the mobile camera using this code:
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for PhoneGap to connect with the device
//
document.addEventListener("deviceready",onDeviceReady,false);
// PhoneGap is ready to be used!
//
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
function onPhotoFileSuccess(imageData) {
// Get image handle
console.log(JSON.stringify(imageData));
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = imageData;
location.href = "#pageone";
}
function capturePhotoWithFile() {
navigator.camera.getPicture(onPhotoFileSuccess, onFail, { quality: 50, destinationType: Camera.DestinationType.FILE_URI });
}
function onFail(message) {
alert('Failed because: ' + message);
}
My problem is that I have a form with text that should take and save a picture. This is my code that adds and saves the form without the image:
function Add(){
var client = JSON.stringify({
repairNum : $("#repairNum").val(),
fname : $("#fname").val(),
lname : $("#lname").val(),
address : $("#address").val(),
});
jewelryRepair.push(client);
localStorage.setItem("jewelryRepair", JSON.stringify(jewelryRepair));
alert("The data was saved.");
return true;
}
My question is, how can I insert the image file in this function add()? Thanks a lot!
Assuming that Add() gets called after onPhotoFileSuccess(), then you can do this in your Add() function (see below). It will be a data url - meaning the url has all of the image data encoded within it.
function Add(){
var client = JSON.stringify({
repairNum : $("#repairNum").val(),
fname : $("#fname").val(),
lname : $("#lname").val(),
address : $("#address").val(),
photoData: $("#smallImage").attr("src")
});
jewelryRepair.push(client);
localStorage.setItem("jewelryRepair", JSON.stringify(jewelryRepair));
alert("The data was saved.");
return true;
}

Is my code below secure enough to be used in production?

What is the best practice to securely upload an image to a php script based on my code below? I'm using the file transfer cordova plugin to upload the image to a php script.
Javascript (file transfer cordova plugin)
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "image/jpeg";
var params = new Object();
params.imageLink = "test";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://example.com/upload.php", win, fail, options);
alert("Post Uploading");
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
alert(r.response);
}
function fail(error) {
$.mobile.loading('hide');
navigator.notification.alert("An error has occurred: Code = " + error.code, null, 'Alert', 'OK');
}
PHP
<?php
if(isset($_POST['imageLink'])) {
$imageLink = $_POST['imageLink'];
print_r($_FILES);
$new_image_name = $imageLink.".jpg";
move_uploaded_file($_FILES["file"]["tmp_name"], “uploads/“.$new_image_name);
}
?>
Any suggestions?
Depends on what to protect from:
Virus/threat pose as image -> use antivirus scanning before upload/save
Somebody snooping the packet in transmit -> use https
Somebody not user try to upload -> your own access control list
Malicous code embedded in image -> again, threat scanner
Above list is just a start though. Security is a rabbit hole that goes down deeper than what we expect it to be.

Categories