I am working on a project which is cropping uploaded image in circle and then save it for preview. Here is also a button for download saved image which is cropped.
Here is my main php page:
<html lang="en">
<head>
<title>PHP - jquery ajax crop image before upload using croppie plugins</title>
<script src="http://demo.itsolutionstuff.com/plugin/jquery.js"></script>
<script src="http://demo.itsolutionstuff.com/plugin/croppie.js"></script>
<link rel="stylesheet" href="http://demo.itsolutionstuff.com/plugin/bootstrap-3.min.css">
<link rel="stylesheet" href="http://demo.itsolutionstuff.com/plugin/croppie.css">
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Image Cropping Area</div>
<div class="panel-body">
<div class="row">
<div class="col-md-4 text-center">
<div id="upload-demo" style="width:350px"></div>
</div>
<div class="col-md-4" style="padding-top:30px;">
<strong>Select Image:</strong>
<br/>
<input type="file" id="upload">
<br/>
<button class="btn btn-success upload-result">Upload Image</button>
</div>
<div class="col-md-4" style="">
<div id="upload-demo-i" style="background:#e1e1e1;width:300px;padding:30px;height:300px;margin-top:30px"></div>
</div>
<div>
<a name="Download Save Image" id="download" download>Download Save Image</a>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$uploadCrop = $('#upload-demo').croppie({
enableExif: true,
viewport: {
width: 200,
height: 200,
type: 'circle'
},
boundary: {
width: 300,
height: 300
}
});
$('#upload').on('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
$uploadCrop.croppie('bind', {
url: e.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
});
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
$.ajax({
url: "ajaxpro.php",
type: "POST",
data: {"image":resp},
success: function (data) {
console.log(data);
var response = JSON.parse(data);
if (response.image) {
html = '<img id="preview" src="' + response.image + '" />';
$("#upload-demo-i").html(html);
$('#download').attr({
target: '_blank',
href: response.image
})
}else {
alert('Failed to upload image');
}
}
});
});
});
</script>
</body>
</html>
and the other for ajax is:
$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$imageName = time().'.png';
if (file_put_contents('upload/' . $imageName, $data)) {
echo json_encode(['image' => 'upload/' . $imageName]); // upload is successful and we return image URL to Javascript
}else {
echo json_encode(['image' => false]); // if upload fails
}
Its functionality is simple and working well.I tried hard to make a simple downloadable button but never found suitable JQuery. Now I am looking for JQuery for my download button to download cropped image. Kindly guide me what part of code I have to put and where.
Thanks for the help. :)
I have changed your Download image button to <a> and given it an id of download and used HTML5 download attribute to force file download
<div>
<a name="Download Save Image" id="download" download>Download Save Image</a>
</div>
Your PHP
$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
$imageName = time().'.png';
if (file_put_contents('upload/' . $imageName, $data)) {
echo json_encode(['image' => 'upload/' . $imageName]); // upload is successful and we return image URL to Javascript
}else {
echo json_encode(['image' => false]); // if upload fails
}
Then in your AJAX get the image URL and set it to the download anchor tag by adding the href and target attributes.
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
$.ajax({
url: "ajaxpro.php",
type: "POST",
data: {"image": resp},
success: function (data) {
console.log(data);
var response = JSON.parse(data);
if (response.image) {
html = '<img id="preview" src="' + response.image + '" />';
$("#upload-demo-i").html(html);
$('#download').attr({
target: '_blank',
href: response.image
})
}else {
alert('Failed to upload image');
}
}
});
});
});
Related
I want to show qrcode on my page, but for performance reasons, I don't want my page loads the qrcode on page load. I put qrcode on bootstrap5 modal box and I want load qrcode when user clicks on the modal botton.
This is my code:
function qrcode($page_id) {
$url = DOMAIN.DS.$page_id;
$size = '256x256';
$color = '000000'; //RGB code without #
$bgcolor = 'ffffff'; //RGB code without #
$margin = '1px';
$width = '36px';
$height = '36px';
if (is_file(FILE.'image'.DS.'icon'.DS.'system'.DS.'qrcode.jpg')) {
$qrthumb = DOMAIN.DS.'file'.DS.'image'.DS.'icon'.DS.'system'.DS.'qrcode.jpg';
} else {
$qrthumb = $qrsrc;
}
$qrcode = '<a href="#" data-bs-toggle="modal" data-bs-target="#qrcode'.$page_id.'">
<img width="'.$width.'" height="'.$height.'" src="'.$qrthumb.'" alt="Scan QR-Code" title="Scan QR-Code" />
</a>
<div class="modal" id="qrcode'.$page_id.'">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body tcenter">
<div id="showqrcode"></div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$("#showqrcode").on("onload", function () {
$.ajax({
type: "POST",
url: "",
success:function(data){
$("#showqrcode").html(data);
}
});
});
});
</script>
';
return $qrcode;
}
function getqrcode($url,$size,$color,$bgcolor,$margin) {
$qrsrc = 'http://api.qrserver.com/v1/create-qr-code/?data='.$url.'&size='.$size.'&color='.$color.'&bgcolor='.$bgcolor.'&margin='.$margin;
$qrimage = '<img width="256px" height="256px" src="'.$qrsrc.'" alt="Scan QR-Code" title="Scan QR-Code" />';
return $qrimage;
}
I want when modal is loading and showing , function getqrcode runs and return the <img...
Thank you
The issue is I can't upload file to the folder but the file name is storing in DB. I am getting an image if I copy and paste an image to the folder but I can't able to upload while update or add an image.
I not good in jQuery. Also, this project using Jquery.file upload plugin which I really don't know.
product-edit.php
<div class="col-sm-6">
<table id="files" class="files">
<tr>
<td>
<div class="col-sm-12 text-center">
<img style="width: 300px; height: 200px;" src="<?= base_url() ?>userfiles/product/<?php echo $product['image'] . '?c=' . rand(1, 9999) ?>"/>
</div>
<div class="col-sm-12 my-2" > <?php echo $product['image'] ?> </div>
<div class="col-sm-12 my-2" >
<a class="btn-danger btn-sm px-1 " data-url="<?= base_url() ?>products/file_handling?op=delete&name=<?php echo $product['image'] ?>" class="aj_delete">
<i class="fa fa-trash mx-1 "></i>Delete Image</a>
</div>
</td>
</tr>
</table>
</div>
<div class="col-sm-6">
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span class="my-2">Select files...</span>
<!-- The file input field used as target for the file upload widget -->
<input id="fileupload" type="file" name="files[]">
</span>
<div class="my-1">
<q>Allowed: gif, jpeg, png</q>
</div>
<!-- The global progress bar -->
<div id="progress" class="progress">
<div class="progress-bar progress-bar-success"></div>
</div>
</div>
</div>
jQuery
<script src="<?php echo assets_url('assets/myjs/jquery.ui.widget.js'); $invoice['tid'] = 0; ?>"></script>
<script src="<?php echo assets_url('assets/myjs/jquery.fileupload.js') ?>"></script>
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = '<?php echo base_url() ?>products/file_handling?id=<?php echo $product['pid'] ?>';
$('#fileupload').fileupload({
url: url,
dataType: 'json',
formData: {'<?=$this->security->get_csrf_token_name()?>': crsf_hash},
done: function (e, data) {
var img = 'default.png';
$.each(data.result.files, function (index, file) {
$('#files').html('<tr><td><a data-url="<?php echo base_url() ?>products/file_handling?op=delete&name=' + file.name + '" class="aj_delete"><i class="btn-danger btn-sm icon-trash-a"></i> ' + file.name + ' </a><img style="max-height:200px;" src="<?php echo base_url() ?>userfiles/product/' + file.name + '"></td></tr>');
img = file.name;
});
$('#image').val(img);
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
Here the controller method for upload file to the folder
Products.php
public function file_handling()
{
if ($this->input->get('op')) {
$name = $this->input->get('name');
if ($this->products->meta_delete($name)) {
echo json_encode(array('status' => 'Success'));
}
} else {
$id = $this->input->get('id');
$this->load->library("Uploadhandler_generic", array(
'accept_file_types' => '/\.(gif|jpe?g|png)$/i', 'max_file_size' => 2048, 'upload_dir' => FCPATH . 'userfiles/product/', 'upload_url' => base_url() . 'userfiles/product/'
));
}
}
The problem is you are loading the upload library config but are not actually processing the upload.
After this, which loads the upload library wih your configuration:
$this->load->library("Uploadhandler_generic", array(
'accept_file_types' => '/\.(gif|jpe?g|png)$/i', 'max_file_size' => 2048, 'upload_dir' => FCPATH . 'userfiles/product/', 'upload_url' => base_url() . 'userfiles/product/'
));
You need to actually process the upload:
if (!$this->upload->do_upload('userfile'))
{
// do something if the upload processing fails. You can output the errors using $this->upload->display_errors()
}
else
{
// do something if the upload is successful
// upload data will be stored in $this->upload->data()
}
By doing this, Codeigniter will take the file from your server's tmp directory and do with it what you want (such as moving it to its destination). Change userfile for the name of the file field.
Please note that if you need to process multiple files at once you'll need to loop through all files (which means a little tweaking on the above code)
I installed BT Property component for my Joomla site and when I select multiple of images (more than 3 or 4) which I want to upload for my article, it nothing happens. The images won't upload. I try to change the code but I don't know what the problem is.
This is the code I want to change.
<?php
defined('_JEXEC') or die('Restricted access');
$document = JFactory::getDocument();
$path = $this->params->get('images_path', 'images/bt_property');
?>
<ul class="adminformlist" id="uploading">
<li><input type="file" name="attachment" id="attachment" multiple /><img id="spinner"
style="display: none; margin-left: 10px;"
src="<?php echo JURI::root(); ?>components/com_bt_property/assets/img/spinner.gif">
<div style="clear: both"></div>
<div id="btss-message"></div></li>
</ul>
<script type="text/javascript">
(function($){
var files = [];
$("#attachment").change(function(event) {
$.each(event.target.files, function(index, file) {
var reader = new FileReader();
reader.onload = function(event) {
object = {};
object.filename = file.name;
object.data = event.target.result;
files.push(object);
if(files.length==1){
uploadFile(index);
$('#spinner').show();
$("#btss-message").show();
}
};
reader.readAsDataURL(file);
});
});
function uploadFile(index){
$.ajax({url: "index.php?option=com_bt_property&task=properties.upload",
type: 'POST',
data: {filename: files[index].filename, filedata: files[index].data},
success: function(response, status, xhr){
uploadHandler(response, status, xhr);
if(index == files.length-1){
$('#spinner').hide();
files = [];
$("#attachment").val('');
$("#btss-message").delay(1000).slideUp(function(){
$("#btss-message").html('');
});
}else{
index++;
uploadFile(index);
}
}
});
}
function uploadHandler(response, status, xhr) {
var data = jQuery.parseJSON(response);
if(data == null){
showMessage("<br /><span style=\"color: red;\">Loading Failed</span>");
}else{
var file = data.files;
if (!data.success) {
showMessage("<br /><span style=\"color: red;\"> " + data.message +"</span>");
}
else {
var html = '<li>';
html += '<input class="input-default" title="Make default" name="default_image" type="radio" value="'+file.filename+'" />';
html += '<img class="img-thumb" src="<?php echo JURI::root() . $path . '/tmp/' . ($this->params->get('thumbimgprocess', 1) == -1 ? 'original' : 'thumb') . '-'; ?>'+file.filename+'" />';
html += '<input type="hidden" name="image_id[]" value="0" />';
html += '<input type="hidden" name="image_filename[]" value="'+file.filename+'" /><br/>';
html +='Edit';
html +='<a href="javascript:void(0)" class="remove" onclick="removeImage(this)" >Remove</a>';
html += '</li>';
jQuery('#sortable').append(html);
jQuery('#sortable li:last-child ').find('a.edit').data('title', file.title);
reNewItem();
showMessage('<br />' + file.title + " uploaded successfully!");
}
}
}
function showMessage(msg){
$("#btss-message").append(msg);
}
})(jQuery);
</script>
Is there a way to fix the code? I would be very thankful for any answer.
Your file object is coming up as undefined, and thus you're not able to use file.filename.
Your problem is most likely with this line var file = data.files; - are you sure about data.files?
We are using jquery.fileApi.js to upload images in a form alongwith Yii Framework. https://rubaxa.github.io/jquery.fileapi/
We have successfully uploaded the images on the server.
Here's the code to upload a file,
<script>
var examples = [];
var imageNames = [];
</script>
<div id="multiupload">
<form class="b-upload b-upload_multi" action="<?php echo $this->createUrl('item/sellNow') ?>" method="POST" enctype="multipart/form-data">
<div class="whiteBox clearfix" id="mulUplImgParent" style="display: none;">
<ul id="sortable" class="js-files b-upload__files">
<li class="col-xs-6 col-sm-2 col-md-2 js-file-tpl b-thumb" data-id="<%=uid%>" title="<%-name%>, <%-sizeText%>">
<header class="clearfix">
<div data-fileapi="file.remove" class="b-thumb__del pull-left"></div>
<% if( /^image/.test(type) ){ %>
<div data-fileapi="file.rotate.cw" class="b-thumb__rotate pull-right"></div>
<% } %>
</header>
<div class="b-thumb__preview">
<div class="b-thumb__preview__pic"></div>
</div>
</li>
</ul>
</div>
<div class="form-group">
<div id="uploadMulImgBtn" class="btn btn-pink btn-small js-fileapi-wrapper">
<span>Browse Images</span>
<input type="file" name="filedata" />
</div>
<figure class="note"><strong>Hint:</strong> You can upload all images at once!</figure>
</div>
</form>
<script type="text/javascript">
examples.push(function() {
$('#multiupload').fileapi({
multiple: true,
url: '<?php echo $this->createUrl('item/uploadImage') ?>',
paramName: 'filedata',
duplicate: false,
autoUpload: true,
onFileUpload: function(event, data) {
imageNames.push(data.file.name);
$("#item-images").val(imageNames.join(','));
},
onFileRemoveCompleted: function(event, data) {
var removeItem = data.name;
imageNames = jQuery.grep(imageNames, function(value) {
return value != removeItem;
});
$("#item-images").val(imageNames.join(','));
},
elements: {
ctrl: {upload: '.js-upload'},
empty: {show: '.b-upload__hint'},
emptyQueue: {hide: '.js-upload'},
list: '.js-files',
file: {
tpl: '.js-file-tpl',
preview: {
el: '.b-thumb__preview',
width: 80,
height: 80
},
upload: {show: '.progress', hide: '.b-thumb__rotate'},
complete: {hide: '.progress'},
progress: '.progress .bar'
}
}
});
});
</script>
</div>
Server Side Code
public function actionUploadImage(){
$userId = Yii::app()->user->id;
$tmpFilePath = $_FILES['filedata']['tmp_name'];
$imageName = $_FILES['filedata']['name'];
$path = 'user_files/';
if(is_dir($path))
{
$dir = $path.$userId;
if(!is_dir($dir))
{
mkdir($dir,0777);
}
$subDir = $dir . '/temp';
if(!is_dir($subDir))
{
mkdir($subDir,0777);
}
$imagePath = "$subDir/$imageName";
move_uploaded_file($tmpFilePath, "$subDir/$imageName");
$image = new Image($imagePath);
$image->resize(190, 190);
$image->save();
$jsonResponse = array('imageName' => $imageName,'imagePath' => $imagePath);
echo CJSON::encode($jsonResponse);
}
//var_dump($_FILES);
//var_dump($_POST);die;
}
We are having issues how to load those images again on the form.
We want to show uploaded images on edit form along with all the event handlers bind through jquery.fileApi .
We cant figure out a way which could render already uploaded images.
Thanks,
Faisal Nasir
I'm trying import images to HTML using PHP, but NivoSlider not loaded that.
I looked for the cause of the problem.
I am printing a alert message of response and the right.
Here is the HTML and AJAX query:
<div id="workcontent" class="pcontent" style="display:none;">
<div class="slider-wrapper theme-default">
<div id="slider" class="nivoSlider">
</div>
</div>
<script>
$(document).ready(function() {
var wl = $('#worklist div');
wl.on('click', function(){
var name = $(this).attr('id');
console.log(name);
$.ajax({
url: 'read.php',
type: 'POST',
data: { data : name }
}).done(function (response) {
$('#slider').prepend(response);
alert(response);
});
});
});
</script>
<div id="back"></div>
<div id="backcontainer">
<div id="back">
Back
</div>
</div><!--End backcontainer-->
</div><!--End content-->
And here is the other jQuery:
<script>
$(document).ready(function() {
$('#slider').nivoSlider(function(){alert('OK');});
});
</script>
This alert don't show! ):
Finally, here is the PHP code:
<?php
if (isset($_POST["data"])){
if ($_POST["data"] == "") {
echo "data ures";
} else {
$data = $_POST["data"];
$fname = "content/".$data."/*.*";
$files = glob($fname);
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
echo '<img src="'.$num.'" data-thumb="'.$num.'">';
}
}
} else {
echo "nem jott data";
}
?>
Sorry for my bad english
NivoSlider doesn't take a function as an argument.
Also .nivoSlider() is probably called before the AJAX call returns it's response.
A better solution would be:
$(document).ready(function() {
$.ajax({
url: 'read.php',
type: 'POST',
data: { data : name }
}).done(function (response) {
$('#slider').prepend(response).nivoSlider( {} );
});
});
Now you can be fairly sure #slider contains the images from the response body so NivoSlider can act on them.