Phonegap blackberry photo upload server php script - php

There are many people asking questions related to this issue, but none are complete enough for me to solve my issue.
I have created a fully working HTML5 smartphone app, based on phonegap, for.. shudder... Blackberry that is sending data nicely to a remote MYSQL server using a server side php script.
However I want to give the option to also upload a photo as this is injury prevention, and hazards need photographing. This is a NON commercial product, it is a working example of modern smartphone technologies and to demonstrate how one app can be ported easily to various smartphones.. Blackberry is the common phone and has to be the prime example.
I cannot for love nor money find any working examples of an app and a php server side script together.
The example I have extracted from the CORDOVA example file takes a picture, and I can see the generated thumbnail in my app, and that bit is all sweet (based on all code you see below), but I dont know what I need to program for my upload.php to do something. Everything I try just fails with error code 3 and 1..
Here is the important code for the webapp.
HTML
<h3>navigator.camera</h3>
<input type="button" value="Get Photo (Data)" onclick="capturePhoto();return false;" />
<input type="button" value="Get Photo (URI)" onclick="capturePhotoURI();return false;" />
<img style="display:none;width:120px;height:120px;" id="cameraImage" src="" />
<p id="uploadProgress"></p>
<input style="display:none;" id="uploadButton" type="button" value="Upload" onclick="uploadImage();return false;" />
JAVASCRIPT
function capturePhotoURI() {
navigator.camera.getPicture(onCapturePhotoURISuccess, fail,
{ destinationType: Camera.DestinationType.FILE_URI, quality: 50 });
}
function onCapturePhotoURISuccess(imageURI) {
if (imageURI != null) {
var smallImage = document.getElementById('cameraImage');
var uploadButton = document.getElementById('uploadButton');
// Unhide image elements
smallImage.style.display = 'block';
uploadButton.style.display = 'block';
// Show the captured photo
// The inline CSS rules are used to resize the image
smallImage.src = imageURI;
}
}
function uploadImage() {
var smallImage = document.getElementById('cameraImage');
if (smallImage.src && smallImage.src !== "") {
var f = new FileTransfer();
f.upload(
// file path
smallImage.src,
// server URL - update to your own, and don't forget to
// include your domain in an access element in config.xml
"http://192.168.1.91/upload.php",
// success callback
function(result) {
document.getElementById('uploadProgress').innerHTML =
result.bytesSent + ' bytes sent';
alert(result.responseCode + ": " + result.response);
},
// error callback
function(error) {
alert('error uploading file: ' + error.code);
},
// options
{ fileName: 'myImage.jpg',
params: { 'username':'jtyberg' }
});
}
}
The server Id above is correct (it is the proper translation of my own development server so I am not using localhost, as I need this to be accurate). Everything you see with the exception of the server IP is vanilla, out the box, unaltered working example from phonegap. The phone is one the same 192 network and defintaly tries to run whatever upload.php I try
Basically I want to take this file, and using the upload.php file move it to
http : // 192.168.1.91/injury/sample_images/xxxx.jpg (spacing http as not sure how to stop it linking)
I have checked rights they are all ok, and my config.html has allow all domains
can anyone please put me out my misery and give me an example upload.php that will use the upload code above and just do something with the camera image.
Once I can get a working example, I can break down exactly what is happening and start the learning process.
Alternativly if someone can provide a working app.. with both app and server side code to use as a tutorial, I am happy to do the studying involved.
Many many thanks in advance for any time people give to this. I am at my wits end, and getting myself in a right muddle when I should be able to get this done.

I decided to use a posting method of the base64 string. I did find however that in this case it was more likely to be the settings on my development server that were the likely cause.

Related

is there any solution for "unable to complete previous operation due to low memory" on file select

Hello I have a web app that is developed in php, ajax. Everything is ok on many of users mobile's web browsers but some of user that use pocof2 pro, has this issue => on file select everything crashes with this message "unable to complete pervious operation due to low memory"
I tried to change the code, even delete everything except input file but getting the same error.
This is my sample code for get image from fileinput
function loadFile(event, img) {
var output = document.getElementById(img);
output.src = URL.createObjectURL(event.target.files[0]);
$("#"+img).css("display", "block");
output.onload = function() {
URL.revokeObjectURL(output.src) // free memory
};
}

Telegram bot weird error : Bad Request: wrong file identifier/HTTP URL specified

I am sending message to telegram channel using bot.
With using webhook method.
I'm sending file_id via the link. I got the file_id from a channel post.
For some files like GIF & video format (MP4),
when i use this code:
$url = 'https://api.telegram.org/bot'.token.'/sendVideo?chat_id='.uid."&video=".$file."&caption="
.urlencode($caption);
file_get_contents($url);
i get such this error :
{"ok":false,"error_code":400,"description":"Bad Request: wrong file identifier/HTTP URL specified"}
I really don't know why i get this,
It's like this is random for errors, Because the code is depended to nothing i guess.
I use file_id that i've got from a channel's post.
What is the reason of that error?
Bad Request: wrong file identifier/HTTP URL specified
I've searched all related topics, I've found NO good information .
There are many possible reasons for this as mentioned in the documentation:
It is not possible to change the file type when resending by file_id. i.e. a video can't be sent as a photo, a photo can't be sent as a document, etc.
It is not possible to resend thumbnails.
Resending a photo by file_id will send all of its sizes.
file_id is unique for each individual bot and can't be transferred
from one bot to another.
Your Awnser is here #farzad
Sending by file_id
file_id is unique for each individual bot and can't be transferred from one bot to another.
Go to #webpagebot and send him an URL to the file. The telegram's cache will be invalidated, and this should work. Seems that it is a bug on the server.
In my case I couldn't upload an image (as sticker), http://.../blabla.webp not via telegram app, not via telegram bot API.
if your url not seen from telegram server or your url is incorrect this error has been seen.
also you can send data to this url with multipart html post method(please fill {YourBotToken} and {your_channel_name_with_Atsign} value):
<form action="https://api.telegram.org/bot{YourBotToken}/sendVideo" method="POST" enctype="application/x-www-form-urlencoded">
<input type="file" name="video" />
<input type="hidden" name="chat_id" value="{your_channel_name_with_Atsign}" />
<button type="submit" >send</button>
</form>
in c# sample code is:
public bool sendVideo(string filename,string sendTo)
{
try
{
var botToken="{YourBotToken}";
var sendTo="{your_channel_name_with_Atsign}";
var filePath = "C:\\sample\\" + filename;
var sendTo, ="#YourChannelNameWithAtSign";
var bytesOfFile = System.IO.File.ReadAllBytes(filePath);
var url = $"https://api.telegram.org/bot{botToken}/sendVideo";
var res =Upload(url, sendTo, "video", bytesOfFile, filename).Result;
}
catch (Exception ex)
{
return false;
}
return true;
}
private static async Task<string> Upload(string actionUrl,string chat_id,string fileParamName, byte[] paramFileStream, string filename)
{
var formContent = new MultipartFormDataContent
{
{new StringContent(chat_id),"chat_id"},
{new StreamContent(new MemoryStream(paramFileStream)),fileParamName,filename}
};
var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(actionUrl.ToString(), formContent);
string stringContent = await response.Content.ReadAsStringAsync();
return stringContent;
}
this way does not need to have a website and you can use that from your stand alone system.
Got the same error, it happens because:
Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
https://core.telegram.org/bots/api#sendvideo
Just try to post another video with file size <= 50 MB.
If you forward a file (photo, audio, ...) to a bot, you will get a valid file_id for this file (for your bot). It should be safe to use this id to send then file, but it seems it dosen't work for some files (audio, video, ...)!! (May be a Telegram API bug).
You can download and reupload the file to your bot, to get a new file_id and this id will work.
In my case, this error occurred because I tried sending an image twice (if the first time it didn't work, I'd reduce the size to under 5mb and send again).
Apparently Telegram caches the previous request, so when a new request to send another image with the same name as the first one arrives, it just returns the previous error without attempting to send it.
To solve it, I gave the resized image a new name (used random + md5 to get a unique string).
In sendDocument, sending by URL will currently only work for GIF, PDF and ZIP files.
https://core.telegram.org/bots/api#sending-files
If you want to send video, only allow .MP4
Another file type, I used sendmessage (but with link inside text).
In my case, for some reason, the error came out when image url has extension full uppercase.
This does not work:
https://example.com/image.JPG
This works:
https://example.com/image.jpg
your mime type video is incorrect change it

How to read a log file live that is constantly updating in server to web textbox

the log file will be in notepad format the values will be like this 11.23445646,56.3456578954
10.23445646,26.3456578954
16.23445646,-46.3456578954
I'm planning to get the data from server to website textbox, of first value which I marked as italic the values will change after few seconds the updated value will come first. I tried some PHP example but not getting it in the below text box the values I need to get.. for example: x=11.23445646, y=56.3456578954, pls guide me
Longtitude <input id="x" type="number" value = "" onkeyup="updateMarker('x')">
Latitude <input id="y" type="number"value = "" onkeyup="updateMarker('y')">
Updated Answer
You can do this now using Web Socketing. Here is a guide and hello-wrold example of a php websocket server:
http://socketo.me/docs/hello-world
And to see how to implement client side javascript of websocket, you can see the bottom of the link put above, which shows you this snippet:
var conn = new WebSocket('ws://localhost:8080');
conn.onopen = function(e) {
console.log("Connection established!");
};
conn.onmessage = function(e) {
console.log(e.data);
};
Old
PHP does not support live connections generally in the way you expect, you have to simulate it via repeated AJAX request. How? For instance on each second, or each two seconds.
You first have to write an ajax in your HTML with jQuery library:
Sending a request each second:
var url = "url_to_you_file";
var textarea_id = "#textarea";
setInterval(function(){
$.ajax({
url : "site.com/get-file-logs.php",
type : "POST",
success : function(data){
$(".textarea").html(data);
}
});
}, 1000);
Then in PHP file you would write this:
$file_path = "path_to_your_file";
$file_content = file_get_contents($file_path);
echo $file_content;
The above example gets the file content and sends it back to your browser. You may want to process it in a certain way; that then changes your approach a little bit. Because you must always stick to JSON format when you try to get data back from server to be manipulated by Javascript.
PHP doesn't really do "live" page updates since normally when a web browser (or other user agent) loads a web page once it's done downloading the page then PHP is already finished and can't touch what's already on the client.
Best way to do this would probably be to use a JavaScript AJAX call to periodically load the updated values from a PHP script and then update the values on the page.
Or if it's a really small page (in byte size) you could just make it automatically reload the whole page (with updated values) if that is not a problem for you.
In any case every time the PHP script is called it would just open the file in read mode and only read the latest values from the beginning of the file and return those. See fread(). Or maybe file_get_contents() or file() would be easier and just read the first line.
AJAX is a bit larger topic and I don't currently have the time to explain the whole process of updating the page using JavaScript. Google is your friend.

Post web image to a server

I've read many posts that due to security risks you cannot upload to your server with an image from your folder as javascript isnt allowed such access. However, I have a situation where i have an svg image on a web site that I convert to a png whilst on the website. But, I wish to send the converted image to my server.
Will I encounter the same problems as if I were uploading from my documents?
I tried to make an example of jsfiddle but it seems it doesnt accept document.write very well, so here's sort of a work-around:
DEMO: jsfiddle
Ideally we would have a button defined as so:
<button id="image" onClick="image()">Convert & Send</button>
Then have the code that does the conversion within a function along with the ajax
function image() {
//conversion code & ajax
}
So in conclusion I would just like to know if this is possible if not, i would be grateful if you could show an alternative way, whether it may include a combination of php.
thanks in advance
It seems as though the fiddle isnt loading heres the snippet: of the conversion
function image () {
var svg = document.getElementById("svg-container").innerHTML.trim();
var canvas = document.getElementById('svg-canvas');
canvg(canvas, svg, { renderCallback: function () {
var img = canvas.toDataURL("image/png");
document.write('<img src="'+img+'"/>');
}
});
I'm not sure about what your question is, but indeed, you can use a combination of Ajax + PHP to upload your image.
The client would POST an encoded image (e.g. encoded in Base64) using ajax (using jQuery.post, for example), while the PHP would receive the image and store it (after decoding it) in your server.
For an example of the process, check this question, where a specific case of a canvas is discussed. I think your SVG conversion could work in a similar way.
PS: For some reason, I couldn't load your Fiddle.
EDIT:
So both Ajax & PHP are written on the front end to send the image to
my server/database (ruby on rails). Is that correct?
No. Only Javascript (with Ajax) is used in the client. PHP would be the server part of the process, so in your case it would not be used as you are already using Ruby on Rails. In other words:
The client (browser) uses Javascript (maybe JQuery) to POST the image data (in your snippet, img) to the server (more info here).
The server (a PHP, ASPX or Ruby script [among others]) gets the POSTed data and saves the picture on disk (some info here).
If you can use PHP (in the server) for the specific process of saving the image, you can use the question I linked before as a guide.
Yes Of Course Their are ways:
I know 2:
1-(This One I know it works on chrome and Firefox but don't know IE):
First Get The Base 64 Data Of An Image In Canvas:
<canvas id="Canv" ....(Other Attributes)>
Your Browser does not support the canvas element :(
</canvas>
<button type="button" OnClick="Image()">Transform and Save</button>
<script type="text/javascript>
var can =document.getElementById('Can');
var ctx = can.getContext("2d");
//do something with ctx
function image(){
//You Should check the real format using img.src
var data = can.toDataURL("image/png");
var array = data.split(".");
var Base64Data = array[1];
//Now step 2 :Sent it to PHP
//Check for Browser compatibly
var ajx = new XmlHttpRequest()
ajx.onreadystatechange=function()
{
if (ajx.readyState==4 && ajx.status==200)
{
if(ajx.ResponseText == "Err"){//if the paged returned error
alert("An error Has Occurred");
return;
}//if not
alert("Saved Succesufuly");
}
}
ajx.open("GET","Save.php?q=" + Base64Data , true);
}
</script>
Step3: Interprete it With PHP
<?PHP
if(isset($_GET['q] And !Empty($_GET['q'])){
try {
$Data = $_GET['q'];
$hndl = fopen("Saved/Pic1.jpg" , "w");
fwrite($hndl , $Data);
fclose($hndl);
}catch(Exception $err){
echo "Err";
}
}else {
echo "Err";
}
?>
Yeap And That it.:D
You Could also loop throught each file in that directory and create a load button that get the Base64 Value And the first stuffs and out it into canvas using pucontent method of canvas element object

Adding unobtrusive progress bar to old-school file uploads

You all know the new generation of fancy, mostly Flash-based file uploaders like SWFUpload that can show a progress bar while uploading - a great improvement especially for shaky and low-bandwidth connections.
However, these uploaders all bring their own logic of how to handle uploads on the client side. I am looking for an unobtrusive way to "fancify" existing, classical file uploads, i.e. introducing a progress bar to normal file upload forms.
Due to the architecture of uploading files, this is most likely not possible without some tweaking on the client side.
I am looking for a solution that keeps the tweaking to an absolute minimum, e.g. a component that adds itself to the onsubmit event of a normal form, performs the file upload, displays a nice progress bar, puts the resulting temporary (server side) file path into the form, and submits it.
On the server side, I just have to modify my script to use the file path provided by the flash uploader, instead of $_FILES and consorts, and think about security for a moment.
This is not exactly what all the Flash-based uploaders do: They can use data from a form, but they do not provide possibilities to submit the form as is, what is what I'm looking for. I am looking for a (probably) Flash based upload function taken a step further.
If you use PHP 5.2 and up this file upload progress tutorial by IBM can help you.
This multiple file upload tutorial uses jQuery + AJAX Upload... It uses $_FILES on the server side and will transform a special <div> on the client side to make a <form>. I guess you could tweak it to fit your needs.
If tweaking the last one is too tricky, Uber-Uploader on SourceForge is another option.
There are dozens of open source project covering this topic. Unfortunately this is not something trivial to implement seamlessly (at least in the way you want - otherwise we would have saw this in the good old Netscape days already).
On the bright side, HTML5 will ease this as you can see in this demo and this one.
I hope this helps and good luck with you integration.
We implemented this very simple by installing the PECL extension pecl-uploadprogress and added a simple AJAX callback to the forms:
Generate an upload key:
$upload_id = genUploadKey();
function genUploadKey ($length = 11) {
$charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
for ($i=0; $i < $length; $i++)
$key .= $charset[(mt_rand(0,(strlen($charset)-1)))];
return $key;
}
Create an AJAX callback handler (eg. uploadprogress.php):
extract($_REQUEST);
// servlet that handles uploadprogress requests:
if ($upload_id) {
$data = uploadprogress_get_info($upload_id);
if (!$data)
$data['error'] = 'upload id not found';
else {
$avg_kb = $data['speed_average'] / 1024;
if ($avg_kb<100)
$avg_kb = round($avg_kb,1);
else if ($avg_kb<10)
$avg_kb = round($avg_kb,2);
else $avg_kb = round($avg_kb);
// two custom server calculations added to return data object:
$data['kb_average'] = $avg_kb;
$data['kb_uploaded'] = round($data['bytes_uploaded'] /1024);
}
echo json_encode($data);
exit;
}
// display on completion of upload:
if ($UPLOAD_IDENTIFIER) {
...
Download jQuery and the jQuery.uploadprogress libraries (which also includes the above snippet) and integrate with your form:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.uploadprogress.0.3.js"></script>
<script type="text/javascript">
jQuery(function () {
// apply uploadProgress plugin to form element
// with debug mode and array of data fields to publish to readout:
jQuery('#upload_form').uploadProgress({
progressURL:'uploadprogress.php',
displayFields : ['kb_uploaded','kb_average','est_sec'],
start: function() {
$('.upload-progress').show();
},
success: function() {
$('.upload-progress').hide();
jQuery(this).get(0).reset();
}
});
});
</script>
Add this to your upload form:
<input name="UPLOAD_IDENTIFIER" type="hidden" value="$upload_id" />
That should do the trick. This is extracted from our code base and may not work out-of-the-box. But it should tell you the idea.
jquploader uses the info inside the form, such as the action attribute value as upload script. But i haven't updated it in a while and it lacks all the belts and whistles scripts like uploadify have (which is an excellent script btw). See if it could be a base for you to tweak.
Does the technique used in Uploadify (a jQuery plugin) meet your needs? Demo
How funny, I just saw Simon Willison blog about Plupload, which is a JavaScript library that I think does file upload progress bars (amongst other things).
It uses Flash, Silverlight, or whatever’s available, but I think abstracts all that away from you, so you’re still uploading with a regular HTML form.
You'll have to check the size of the part of the file wich is allready on the Server, then get it on the Client per Ajax where you can paint the progress bar. (Remember to check the size of the hole Data before, to calculate the percantage ;-) )

Categories