My requirement is to save the images taken from Camera of Cordova plugin and save the image in a server . I have used below code and achieved getting the image , but how do i save in a server using PHP
// Code to capture photo from camera and show gps co ordinates
<!DOCTYPE html>
<html>
<head>
<title>Capture Photo</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for device API libraries to load
document.addEventListener("deviceready",onDeviceReady,false);
// device APIs are available
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
//
function onPhotoDataSuccess(imageData) {
// Uncomment to view the base64-encoded image data
// console.log(imageData);
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
smallImage.src = "data:image/jpeg;base64," + imageData;
}
// Called when a photo is successfully retrieved
//
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;
}
// A button will call this function
//
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: destinationType.DATA_URL });
}
// A button will call this function
//
function capturePhotoEdit() {
// Take picture using device camera, allow edit, and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}
// A button will call this function
//
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
// Called if something bad happens.
//
function onFail(message) {
alert('Failed because: ' + message);
}
</script>
</head>
<body>
// button to capture photo
<button onclick="capturePhoto();">Capture Photo</button> <br>
// button to capture editable photo
<button onclick="capturePhotoEdit();">Capture Editable Photo</button> <br>
//button to select images from library
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
</body>
</html>
PHP Code (upload.php):
<?php
print_r($_FILES);
move_uploaded_file($_FILES["file"]["tmp_name"], "192.168.3.153/uploads/".$_FILES["file"]["name"]);
?>
The only way to do this is to get the image as a Base64 encoded string, send that back to the server and then save it into the DB, either in encoded form, or decode it and then save it as a file on the server or a blob in a database.
I don't know the exact implementation procedure as I'm not a Cordova dev, I just sit next to one at work who was tearing his hair out over something similar recently.
In cordova we have plugin file transfer which is used to download / upload files from server. You have to use this plugin to upload image taken from camera.
Check following link that details how to upload file to server
Following is a Javascript function that picks a file stored in mobile device and send it to server
function uploadfiletoserver(filename){ // where filename is the file store in device
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
//The folder is created if doesn't exist
fileSys.root.getDirectory( 'APP STORAGE FOLDER', {create:true, exclusive: false},
function(directory) {
//find the file
directory.getFile(filename, {create: false, exclusive: false},
function(file){
var imageURI = file.toInternalURL();
var options = new FileUploadOptions();
options.fileKey = "uploadfile"; //this is the value use to refer the file uploaded to server e.g. $_FILES['uploadfile']
options.fileName = file.name;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI('http://www.yourdomain.com/upload.php'), function (r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}, function (error) {
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}, options);
console.log("upload file: "+imageURI);
},
function(error){
console.log("Error "+error);
}
);
},
resOnError);
},
resOnError);
}
In server PHP file,
<?php
$tmpName = $_FILES['uploadfile']['tmp_name'];
$fileName = $_FILES['uploadfile']['name'];
$fileDestPath = 'YOUR_UPLOAD_FOLDER_IN_SERVER'.$fileName;
if($tmpName != 'none') {
move_uploaded_file($tmpName, $fileDestPath);
}
?>
Related
Here is my code. i want to upload the image file using ajax, php. when the image file is uploaded it should show the preview. The image file is successfully uploading but the ajax success is not showing the preview.
Here is my form code:
<form method="post" enctype="multipart/form-data">
<div class='preview'>
<img src="" id="photo_disp" width="100" height="100">
</div>
<input type="file" name="file1" id="file1" accept=".jpeg,.jpg" required/>
<button type="submit" id="btn_photo" name="submit">Upload Photo</button>
</form>
Here is the ajax i have used. The ajax is successfully posting the file to php code but the success response is not working.
<script>
$(document).on('click','#btn_photo',function(){
var fd = new FormData();
var files = $('#file1')[0].files;
// Check file selected or not
if(files.length > 0 )
{
fd.append('file',files[0]);
$.ajax({
url:'ajax_photo.php',
type:'post',
data:fd,
contentType: false,
processData: false,
success:function(response)
{
alert(response);
if(response != 0)
{
$("#photo_disp").attr("src",response);
}
else
{
alert('File not uploaded');
}
}
});
}
else
{
alert("Please select a file.");
}
});
</script>
Here is my php code using on click
<?php
if(isset($_FILES['file']['name']))
{
session_start();
$filename = $_FILES['file']['name'];
$roll=$_SESSION['name'];
$imageFileType = pathinfo($filename,PATHINFO_EXTENSION);
$imageFileType = strtolower($imageFileType);
$valid_extensions = array("jpg","jpeg");
$response = 0;
if(in_array(strtolower($imageFileType), $valid_extensions))
{
$location = "upload/".$roll.".".$imageFileType;
if(move_uploaded_file($_FILES['file']['tmp_name'],$location))
{
$response = $location;
}
}
echo $response;
exit;
}
echo 0;
?>
Please find out where i did the mistake. The image is successfully uploading to the given path but the image is not showing in the preview. i have written an alter in the success. But the alert is also not working.
If the response refers to a fully qualified resource path (https:example.com/upload/cat-dancing.jpg) on the server, you can assign it directly to the image's src attribute just like you've done in your question.
$("#photo_disp").attr("src",response);
If the returned resource path doesn't contain the domain name (upload/cat-dancing.jpg), prepend it with a forward slash to indicate that the path starts from the document root of the website. I.e:
$("#photo_disp").attr("src", "/" + response);
Otherwise, if the response is an actual File or Blob, you could set the image's src attribute using:
const img = $("#photo_disp").get(0);
img.src = URL.createObjectURL(response);
img.height = 60;
img.onload = function() {
URL.revokeObjectURL(this.src);
}
Set the image's source to a new object URL representing the file, using
URL.createObjectURL()
to create the blob URL.
Set the image's height to 60 pixels.
Set up the image's load event handler to release the object URL since it's no longer needed once the image has been loaded. This is
done by calling the
URL.revokeObjectURL()
method and passing in the object URL string as specified by img.src.
Resource:
Example: Using object URLs to display images
this is what i want onclick:
this is what i get onclick:
Im using this script for capturing image in php:
<script type="text/javascript">
$(function()
{
$('#capture').click(function(){
//get the div content
//proxy: "html2canvasproxy.php",
useCORS: true,
div_content = document.querySelector("#map_canvas")
//make it as html5 canvas
html2canvas(div_content).then(function(canvas) {
//change the canvas to jpeg image
data = canvas.toDataURL('image/jpeg');
//then call a super hero php to save the image
save_img(data);
});
});
});
function save_img(data)
{
$.post('save_jpg.php', {data: data}, function(res)
{
if(res != '')
{
yes = confirm('File saved in output folder, click ok to see it!');
}
else
{
alert('something wrong');
}
});
}
</script>
as you can see if i used proxy that i download from github nothing
will capture. and if i comment that part map will capture but not as
per my conditions.
Im using it on live server with php html5 and css3
I need a code that can instant upload an image from the pc to my website after I select it without needet to click submit or to refresh the page. This is the code that I have until now!
<img id="uploadPreviewprofile" style="max-width: 990px; max-height: 320px;text-align:center; position:absolute;" />
<div class="fileUploadprofile btn btn-primary" style="position:absolute; margin-top:298px;">
<form method="post" enctype="multipart/form-data">
<input id="uploadImageprofile" type="file" name="fotoprofile" class="uploadprofile" onchange="PreviewImageprofile();" />
</div>
<script type="text/javascript">
function PreviewImageprofile() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImageprofile").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadPreviewprofile").src = oFREvent.target.result;
};
};
</script>
</div>
Just ajax it over to your server after you read the file, e.g.:
HTML
<input id="instant" type="file">
JavaScript
// Note: I am using jQuery here, so you need to include the library
$("#instant").on("change", function() {
$.each(this.files, function(index, file) {
// read file data
reader = new FileReader();
reader.onload = function(event) {
// send to server
$.post("upload.php", {name: file.name, image: event.target.result});
}
reader.readAsDataURL(file);
});
});
PHP
<?php
if($_POST["image"]) {
// image is base64 encoded, so let's unparse it
$parts = explode(",", $_POST["image"]);
// check that we have the image
if(isset($parts[1])) {
// save the image
file_put_contents($_POST["name"], base64_decode($parts[1]));
}
}
And that's all the magic..
Quick recap:
1) We select the image via standard file upload tag
2) We capture the change the push the base64 encoded image to the server using an AJAX Post
3) We parse the base64 encoded image (which is in the Data URI scheme) and decode the base64 data part of it. This will give us the binary data from the actual image/file to save to the hard drive using the original name of it.
Now this code doesn't have any checks, etc. But it gives you the core functionality to continue your work.
PHP FILE:
<?php
#Communication with the API
require_once 'api.php';
$cloudkey = new CloudKey($user_id, $api_key);
if(isset($_FILES["FileInput"]) && $_FILES["FileInput"]["error"]== UPLOAD_ERR_OK)
{
//Deleted Code: putting the uploaded files in my server.
if(move_uploaded_file($_FILES['FileInput']['tmp_name'], $UploadDirectory.$NewFileName ))
{
$video_file = "/home/george/public_html/q/";
$video_file = $video_file . $NewFileName;
#Sending the video from my server to the cloud server
$res = $cloudkey->file->upload_file($video_file);
#The cloud server will create a link
$source_url = $res->url;
#The cloud server will convert the video very fastly
while(1) {
#Deleted Code: Conversion
if ($asset->status == 'ready') {
# A lot of code. It will convert the videos here and if it succeeds it will stop.
break;
# If the conversion fails, display error
} else if ($asset->status == 'error') {
echo "Error while transcoding the media\n";
}
sleep(1);
}
# Getting the URL of a thumbnail
echo $thumb = $cloudkey->media->get_stream_url(array('id' => $media_id, 'asset_name' => 'jpeg_thumbnail_source'));
}else{
die('error uploading File!');
}
}
else
{
die('Something went wrong!');
}
?>
HTML FILE:
{literal}
<script type="text/javascript">
$(document).ready(function() {
var options = {
target: '#output', // target element(s) to be updated with server response
beforeSubmit: beforeSubmit, // pre-submit callback
success: afterSuccess, // post-submit callback
uploadProgress: OnProgress, //upload progress callback
resetForm: true // reset the form after successful submit
};
//function after succesful file upload (when server response)
function afterSuccess()
{
$('#loading-img').hide(); //hide submit button
$('#progressbox').fadeOut(); //hide progress bar
//I WANT TO INSERT SOMETHING HERE.
}
//progress bar function
function OnProgress(event, position, total, percentComplete)
{
//DOES NOT INTEREST YOU
});
</script>
{/literal}
<div id="output"></div>
I am using smarty template engine. I have an html upload form that will communicate with a php file progressupload.php where the php file will convert the video (using API services) and brings back a response when it finishes.
When the user uploads the video file, ajax will take over show the percentage (in html), and it will send the file to progressupload.php and when the progressupload.php finishes the conversion it will output everything echoed in the php by simply putting this in the html file (I don't know why): <div id="output"></div>.
WHAT I WANT:
When progressupload.php finishes the conversion, it will generate a thumbnail (screenshot) and store its link in $thumb. I want to retrieve $thumb and show it to the user using jquery.
Now if you look at the HTML Code, afterSuccess() is the function where I want to show the thumbnail to the user:
function afterSuccess()
{
$('#loading-img').hide(); //hide submit button
$('#progressbox').fadeOut(); //hide progress bar
//I WANT TO SHOW THE THUMBNAIL HERE.
}
I deleted a lot of unnecessary code that could've distracted you. Remember that I am using smarty template engine, my html file does not end with .php, I cannot echo the variable directly. How can I retrieve the php variable and put it in a jquery method after the variable is created.
I have a suspicion that if you retrieve the variable directly on page load, it will not succeed in getting $thumb since the link needs time to be created (uploading, conversion). How can I retrieve that $thumb?
Assuming that you are using jQuery.ajax();
First parameter in the $.ajax 'success' callback is what returned from the server side.
function afterSuccess( response /** this is what returned from your server **/ )
{
$('#loading-img').hide(); //hide submit button
$('#progressbox').fadeOut(); //hide progress bar
//I WANT TO INSERT SOMETHING HERE.
console.log(response); // here you can access your $thumbnail
// below code is untested but it should work
// $("#output").html("<img src='"+response+"' class='thumbnail' />");
}
I am dealing with a form that contains various form elements with an option to upload multiple images(upto 6 max). Now i am having a div preview on clicking that div i fetch all form fields using jquery (form still not submitted at this time as its a multi form step1, 2 and 3). Now the problem is that i am fetching all form data with this code -
var allFormData = $("#myform").serializeArray();
Using this another code i am able to show rest of the data in div, but image is not coming.
$.each(adtitletoshow, function(i, field){
if( field.name == 'desc'){
$(".add_desc").text(field.value);
}
});
This is the filed created by JS to upload image.
<script type="text/javascript">
var total_images = 1 ;
function add_file_field () {
total_images++ ;
if ( total_images > 6 ) return ;
var str_to_embed = '<input name="fileImage[]" size="40" style="width: 500px;" type="file" onChange="add_file_field()"><br>' ;
$("#image_stack").append ( str_to_embed ) ;
}
</script>
All things going on single page so i need a solution that how can i load images under my preview div. Let me know if thr is some point of ambiguity still persists.
You need to loop through the files array from the multiple input and use the FileReader API on each.
I've set up the HTML like this:
<input type="file" multiple="true" id="files" />
<input type="submit" id="go"/>
<div id="images"></div>
Then the javascript as follows:
// set up variables
var reader = new FileReader(),
i=0,
numFiles = 0,
imageFiles;
// use the FileReader to read image i
function readFile() {
reader.readAsDataURL(imageFiles[i])
}
// define function to be run when the File
// reader has finished reading the file
reader.onloadend = function(e) {
// make an image and append it to the div
var image = $('<img>').attr('src', e.target.result);
$(image).appendTo('#images');
// if there are more files run the file reader again
if (i < numFiles) {
i++;
readFile();
}
};
$('#go').click(function() {
imageFiles = document.getElementById('files').files
// get the number of files
numFiles = imageFiles.length;
readFile();
});
I've set up a JSFiddle to demo http://jsfiddle.net/3LB72/
You'll probably want to do more checks on whether the browser the user is using has FileReader and if the files they have chosen are image files.
JSFiddle demo
This is much better, without clicking any button :D
HTML:
<input type="file" multiple="true" id="files" />
<input type="submit" id="go"/>
<div id="images"></div>
JavaScript:
// set up variables
var reader = new FileReader(),
i=0,
numFiles = 0,
imageFiles;
// use the FileReader to read image i
function readFile() {
reader.readAsDataURL(imageFiles[i])
}
// define function to be run when the File
// reader has finished reading the file
reader.onloadend = function(e) {
// make an image and append it to the div
$("#images").css({'background-image':'url('+e.target.result+')'});
// if there are more files run the file reader again
if (i < numFiles) {
i++;
readFile();
}
};
$('#files').live('change', function(){
imageFiles = document.getElementById('files').files
// get the number of files
numFiles = imageFiles.length;
readFile();
});