Load the Images using jquery File Api - php

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

Related

File upload with Jquery.fileupload.js in CodeIgniter - I can't find my error

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)

JQuery For Download Button

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

Angular JS posting image and hidden field data to php

I am facing a problem in accessing the value of hidden field.
I have made an image cropping application in which i am asking the user to upload an image and a UI is provided to help the user to select the area to crop. Then the top left x and y coordinate and the width and height of the selected area is stored as a semicolon separated string in a hidden input field and when the 'Crop' button is clicked the image and the hidden filed value is passed to the crop.php file. But the values of the hidden field is not accessible in the php file.
My html file which provides browse and crop functionality -
<!doctype html>
<html>
<head>
<title>
Crop
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript" src="scripts/jquery.imgareaselect.pack.js"></script>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/imgareaselect-default.css" />
<script>
var app = angular.module('main-App',[]);
app.controller('AdminController', function($scope, $http) {
$scope.form = [];
$scope.files = [];
$scope.progressBar=0;
$scope.progressCounter=0;
$scope.submit = function() {
alert('Sub');
$scope.form.image = $scope.files[0];
$http({
method : 'POST',
url : 'crop.php',
processData: false,
transformRequest: function (data) {
var formData = new FormData();
formData.append("image", $scope.form.image);
return formData;
},
data : $scope.form,
headers: {
'Content-Type': undefined
},
uploadEventHandlers: {
progress: function (e) {
if (e.lengthComputable) {
$scope.progressBar = (e.loaded / e.total) * 100;
$scope.progressCounter = $scope.progressBar;
$("#completion").css("width", $scope.progressBar+'%');
}
}
}
}).then(function successCallback(response) {
alert($scope.form.params);
});
};
$scope.uploadedFile = function(element) {
$scope.currentFile = element.files[0];
var reader = new FileReader();
reader.onload = function(event) {
$scope.image_source = event.target.result
$scope.$apply(function($scope) {
$scope.files = element.files;
});
}
reader.readAsDataURL(element.files[0]);
$('img#photo').imgAreaSelect({
onSelectStart: {enable:true},
onSelectEnd: function (img, selection) {
document.getElementById("params").value=selection.x1+';'+selection.y1+';'+selection.width+';'+selection.height;
alert(document.getElementById("params").value);
}
});
}
});
</script>
<style>
html,body {
height: 100%;
}
.wrapper{
height:auto;
}
.wrapper img {
height:100%;
color:grey;
text-align: center;
line-height:100px;
vertical-align: middle;
padding:0px;
margin:0px;
}
</style>
</head>
<body>
<div ng-app="main-App" ng-controller="AdminController">
<form ng-submit="submit()" name="form" role="form" enctype="multipart/form-data">
<div class="container-fluid">
<div class="row flex-items-xs-center">
<div class="col-md-9">
<div class="container-fluid">
<div class="row">
<div class="col-md-9">
<div class="wrapper">
<img id="photo" name="photo" src="{{image_source}}" alt="Image preview..." class="img-responsive img-thumbnail" style="border-style:dashed">
</div>
</div>
</div>
</div>
<br/>
<br/>
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
<label class="btn btn-primary">
<input ng-model="form.image" type="file" class="form-control input-lg" name="image" id="image"
accept = "image/*"
onchange="angular.element(this).scope().uploadedFile(this)"
style="display:none;" >
<span class="glyphicon glyphicon-folder-open"></span>
Browse
</label>
</div>
<div class="col-md-2">
<label class="btn btn-success">
<input type="submit" id="submit" value="Submit" style="display:none;"/>
<span class="glyphicon glyphicon-cloud-upload"></span>
Crop
</label>
</div>
</div>
</div>
</div>
</div>
</div>
<input type="hidden" name="params" id="params" value="0;0;0;0" ng-model="params" />
</form>
<br/>
<br/>
<div class="container-fluid">
<div class="row">
<div class="col-md-9">
<div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar" id ="completion" name="completion"
aria-valuenow="0" aria-valuemin="0" aria-valuemax="50" style="width:0%;height:10px;border-width:0px;border-radius:2px;">
</div>
</div>
</div>
</div>
</div>
<br/>
<br/>
the UI -
crop.php -
<?php
$uncropped_path = '/var/www/html/images/original/';
$cropped_path = '/var/www/html/images/cropped/';
if(isset($_FILES['image'])){
//$ext = pathinfo($_FILES['image']['name'],PATHINFO_EXTENSION);
$image = $_FILES['image']['name'];
move_uploaded_file($_FILES["image"]["tmp_name"], $uncropped_path.$image);
$data = json_decode(file_get_contents("php://input"));
print_r($data);
}else{
echo "Image Is Empty";
}
function doResize($filename,$size,$resize_path)
{
$image = new Imagick();
$file = file_get_contents($filename);
$image->readImageBlob($file);
$dimensions = $image->getImageGeometry();
$pathInfo = pathinfo($filename);
$name = $pathInfo['filename'];
$srcWidth = $dimensions['width'];
$srcHeight = $dimensions['height'];
list($resWidth,$resHeight) = getResizeDim($size,$srcWidth,$srcHeight);
$image->resizeImage($resWidth,$resHeight,Imagick::FILTER_LANCZOS,.85);
$image->writeImage($resize_path);
}
function getResizeDim($size,$srcWidth,$srcHeight)
{
$width;
$height;
if($srcHeight > $srcWidth)
{
if($srcHeight > $size)
$height = $size;
else $height = $srcHeight;
$width = ceil($height*($srcWidth/$srcHeight));
}
else {
if($srcWidth > $size)
$width = $size;
else $width = $srcWidth;
$height = ceil($width*($srcHeight/$srcWidth));
}
return array($width,$height);
}
When i try to print the data received in php i get the following -
Moreover the data array in the php seems to be empty.
I have read various similar questions on stackoverflow but none of them worked in my case.

Plupload: get data attributes of multiple dynamic dropzones

I am working on a project where we are using a single instance of plupload to handle the uploads from multiple dropzones that are dynamically generated. We use Smarty templates, jQuery and PHP. There are a couple attributes that need to be carried over throughout the process as once the upload to the server hosting the application is successful, a transfer of the documents happens, transferring the document to AWS. I am struggling to understand how I can collect the need attributes during the initial upload through plupload. Currently, the files upload fine to the local server.
What I need is to get the id of the row, and the data-type attribute of the dropped-on row. You can see in the opening li the attributes id={$doc.id} and data-type={$doc.id}; these are the attributes I need to collect. Here is the markup for the form:
{foreach $document_set as $doc}
<li id="file-{$doc.id}" class="doc_list_row" data-type="{$doc.id}">
<div class="row doc_list_row">
<div class="col-sm-12" style="color: #fff">
<div class="row">
<div class="col-sm-12 doc_list_title">
<h4>{$doc.name}</h4>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<div class="row">
<div class="col-sm-8 padtop-10">
<p>{$doc.description}</p>
</div>
</div>
<div class="row file_details_row">
<div class="col-sm-6">
<h4>Created On:</h4>
<p>{$doc.created}</h4>
</div>
<div class="col-sm-6">
<h4>Created By:</h4>
<p>{$doc.created_by}</p>
</div>
</div>
<div class="row file_details_row">
<div class="col-sm-6">
<h4>Updated On:</h4>
<p>{$doc.last_update}</h4>
</div>
<div class="col-sm-6">
<h4>Updated By:</h4>
<p>{$doc.last_update_by}</p>
</div>
</div>
</div>
<div class="col-sm-4 mng_file_icon_container">
<div class="row">
<div id="dl-{$doc.id}" class="col-xs-6 col-sm-6 dl_icon" data-filename="fileURLWillGoHere">
<div id="dl_circle-{$doc.id}" class="dl_circle circle">
<div class="triangle-down">
</div>
<h3 class="dl_version">V.{$doc.version_depth}</h3>
</div>
</div>
<div class="col-xs-6 col-sm-6 upld_icon" data-toggle="modal" data-target="#upld_file_modal">
<div id="upld_circle-{$doc.id}" class="upld_circle circle">
<div class="triangle-up">
</div>
<h3 class="upld_version">V.{$doc.version_depth + 1}</h3>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</li>
{/foreach}
Here is the jQuery to handle this handoff:
var dom = { uploader: $("#dropbox"),
uploads: $("ul.doc_list_container"),
dropzones: $("li.doc_list_row")
};
uploader = new plupload.Uploader({
runtimes : "html5,silverlight,html4",
browse_button : "file-pick",
container : "file-cntr",
max_file_zie : '10mb',
url : "../upload.php",
drop_element: "dropbox",
filters : {title : "Text Files", extensions : "pdf, doc, docx, xls, xlsx, ppt, pptx"},
init: {
FilesAdded: function(up, files){ up.start(); $("#file-upld-progress").fadeIn(300); },
UploadProgress: function(up, file){ $("#file-upld-progress").text(file.percent + "%"); },
UploadComplete: function(up, file) { $("#file-upld-progress").fadeOut(300, function(){ setTimeout(function(){ $("#file-upld-progress").text(''); }, 2500); }); },
FileUploaded: function(up, file, resp, src) { uploadHandler(resp.response, src); },
Error: function(up, err) { showFormMsg("alert-error", "File Upload Error #" + err.code + ": " + err.message); }
},
multipart: true,
multipart_params : {}
});
uploader.bind("BeforeUpload", handlePluploadBeforeUpload);
uploader.bind("PostInit", handlePluploadInit);
uploader.bind("FilesAdded", handlePluploadFilesAdded);
uploader.init();
uploader.bind("FileUploaded", function(up, file, resp) { uploadHandler(resp.response); });
var fileType = '';
dom.dropzones.each(function(){
var dropzone = new mOxie.FileDrop({
drop_zone: $(this).attr('id')
});
dropzone.ondrop = function(e){
uploader.addFile(this.files);
// fileType = $(this);
};
dropzone.init();
var input = new mOxie.FileInput({
browse_button: $("#file-pick")[0],
container: this,
multiple: true
});
input.onchange = function(e){
uploader.addFile(input.files);
};
input.init()
});
function handlePluploadBeforeUpload( uploader, file ) {
params = uploader.settings.multipart_params;
var source = file.getSource();
// console.log(source);
// console.log(params.docType);
}
function handlePluploadInit(uploader, params){
// console.log("Initialization complete.");
// console.log("Drop-drop supported:", !! uploader.features.dragdrop);
}
function handlePluploadFilesAdded( uploader, files ) {
for ( var i = 0 ; i < files.length ; i++ ) {
files[i].docType = $(this).data('type');
}
}
And upload.php:
<?php
session_start();
require_once(dirname(dirname(__DIR__)).'/sites/site_settings.php');
//Output passed values from plUpload
/*$fh = fopen("./request.txt",'w');
fwrite($fh, "Request Dump\n");
fwrite($fh, print_r($_REQUEST, true));
fwrite($fh, "\n\nPost Dump\n");
fwrite($fh, print_r($_POST, true));
fwrite($fh, "\n\nGET Dump\n");
fwrite($fh, print_r($_GET, true));
fwrite($fh, "\n\nServer Dump\n");
fwrite($fh, print_r($_SERVER, true));
fwrite($fh, "\n\nFiles Dump\n");
fwrite($fh, print_r($_FILES, true));
fclose($fh);*/
if($_SERVER['REQUEST_METHOD'] == "POST")
{
if(! empty($_FILES['file']))
{
if($_FILES['file']['error'] === UPLOAD_ERR_OK)
{
$path_info = pathinfo($_FILES['file']['name']);
$file_extension = strtolower($path_info["extension"]);
$extension_whitelist = array("pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx");
$doc_fk = $_FILES['file']['doc_fk'];
if(in_array($file_extension, $extension_whitelist))
{
try
{
$url = ADMIN_URL."/documents/temp/";
$path = ADMIN_PATH."/documents/temp/";
$fname = cleanFilename($_FILES['file']['name']);
if(move_uploaded_file($_FILES["file"]["tmp_name"], $path.$fname))
$ret = array("error" => 0, "path" => $url, "givenName" => $_FILES['file']['name'], "storedName" => $fname, "ext" => $file_extension, "doc_fk" => $doc_fk);
else
$ret = array("error" => 1, "error_msg" => "Failed to Upload File to System");
}
catch(Exception $e)
{
$ret = array("error" => 1, "error_msg" => $e->getMessage());
}
}
else
$ret = array("error" => 1, "error_msg" => "Invalid file type: $file_extension. File must be PDF, Word Document, Excel Spreadsheet or a PowerPoint Presentation.");
}
else
$ret = array("error" => 1, "error_msg" => "Upload Error Occurred");
}
}
else
$ret = array("error" => 1, "error_msg" => "Failed POST check: ".$_SERVER[REQUEST_METHOD]);
echo json_encode($ret);
?>
Once I understand how to collect those two attributes, I will be able to move forward with completing this part of the project. This is the last hangup, and has absorbed several hours of trial and error, following a variety of GitHub articles, and SO threads. I've also referred to plupload's forums and haven't encountered anything quite similar to what we are doing here. TIA for any assistance!
Here's the solution we managed to come up with for our use case in this scenario. With our jQuery, we create an array of uploaders. This is where our dynamically generated uploader's id's will be stored. Then for each potential uploader, we instantiate a new uploader. Considering we iterate on the doc_list_row class, we are able to acquire the individual id of each list row, and place this in drop_element.
Everything else from here south is essentially the same as a typical plupload instance.I included our uploadHandler function simply for reference, it is not necessary if you handle the upload success differently. Keep in mind we use smarty templates and xajax, so if you use standard ajax, or another language other than PHP for you backend, some of this code will not directly work for you! I hope this helps others in a similar situation figure out the next step as this use case was a bit difficult to conquer.
jQuery
/*******************************************************************************
*
* Upload Document
*
*
*******************************************************************************/
function initUploaders(){
if($("li.doc_list_row").length){
upldrs = new Array();
$("li.doc_list_row").each(function(){
upld = new plupload.Uploader({
runtimes : "html5",
url : "upload.php",
dragdrop: true,
drop_element : $(this).attr("id"),
browse_button : $(this).find("div.upld_icon").attr("id"),
filters: {
max_file_size : '10mb',
mime_types: [{title : "Scan Files", extensions : "pdf,jpg,jpeg,png,xls,xlsx,doc,docx"}]
},
multipart_params : {DOC_ID: $(this).attr("data-doc")},
init: {
// FilesAdded: function(up, files){ up.start(); },
FilesAdded: function(up, files){ up.start(); showProgressBar(up); },
UploadProgress: function(up, file){ $(".upld-progress").css("width", file.percent + "%"); },
UploadComplete: function(up, file) { hideProgressBar(); },
FileUploaded: function(up, file, resp) { uploadHandler(resp.response); },
Error: function(up, err) { showFormMsg("alert-error", "File Upload Error #" + err.code + ": " + err.message); }
}
});
upld.init();
upldrs.push(upld);
});
}
}
/*******************************************************************************
*
* Response handler for plupload
*
*
*******************************************************************************/
function uploadHandler(resp){
var r = $.parseJSON(resp);
if(r.error)
showFormMsg("alert-danger", "Upload Error: " + r.error_msg);
else{
var elemId = $(upld.settings.drop_element[0]).attr('id').split('-');
showFormMsg('alert-success', 'Upload successful.');
xajax_paginate(currentPage(), currentDept(), $("#filter-doc-category").val(), $("#search_doc_name-id").val().trim(), $("#search_publisher_name-id").val().trim());
$("#file-"+elemId).find('.unavail_dl_icon').removeClass('unavail_dl_icon').addClass('dl_icon');
}
}
HTML
{if $documents_set|default:0}
{foreach $documents_set as $doc}
<li id="file-{$doc.id}" class="doc_list_row" data-doc="{$doc.id}" data-ondeck="0" data-default="{$doc.name}">
<div class="row doc_list_row">
<div class="col-sm-8">
<div class="row">
<div class="col-sm-12 doc_list_title">
<div class="col-sm-3"><h4>{$doc.name}</h4></div>
<div class="col-sm-4" style="padding-top: 15px; margin-bottom: 0;">
<div id="doc-upld-bar-{$doc.id}" class="progress upld-progress">
<div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:100%"></div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-8">
<div class="row">
<div class="col-sm-8 padtop-10">
<p>{$doc.description}</p>
</div>
</div>
<div class="row file_details_row">
<div class="col-sm-6">
<h4>Last Update:</h4>
<p>{$doc.lastUpdate}</p>
</div>
<div class="col-sm-6">
<h4>Last Update By:</h4>
<p>{$doc.last_update_by}</p>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-4">
<div class="row">
<div class="col-sm-12 mng_file_icon_container">
<div id="dl-{$doc.id}" class="col-xs-6 col-sm-6 {if $doc.file_list|default:''}dl_icon{else}unavail_dl_icon{/if}" data-doc="{$doc.id}">
<!-- This is the selector -->
{if $doc.file_list|default:''}
<select id="version-selector-{$doc.id}" class="available_versions">
{foreach $doc.file_list as $f}<option value="{$f}">{if $f#first}Current{else}{$f#index} Previous{/if}</option>{/foreach}
</select>
<div id="dl_circle-{$doc.id}" class="dl_circle circle" data-for="{$doc.file}">
<div class="triangle-down">
</div>
</div>
{else}
<select class="no_file" DISABLED>
<option>No File</option>
</select>
<div id="unavail_dl" class="unavail_dl_circle circle">
<div class="unavail_triangle">
</div>
</div>
{/if}
</div>
<div id="upld-{$doc.id}" class="col-xs-6 col-sm-6 upld_icon">
<div id="upld_circle-{$doc.id}" class="upld_circle circle">
<div class="triangle-up">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</li>
{/foreach}

Blueimp file upload plugin, progress bar completes before file is uploaded

I'm using this plugin to upload files:
https://github.com/hashmode/cakephp-jquery-file-upload
The upload works, but the progress bar always completes before the file is uploaded. Prior to using this plugin, I attempted to use the blueimp uploader standalone. I had the same problem.
Any idea how to make the progress bar work properly?
I'm testing this via a proxy. I can see the proxy is still awaiting the response. Yet the progress bar is 100%.
This is the code I'm using in my view:
<?php echo $this->JqueryFileUpload->loadCss(); ?>
<?php echo $this->JqueryFileUpload->loadScripts(); ?>
<div class="row">
<div class="col-md-12">
<div class="card ">
<div class="header">
<h4 class="title">Import Session Data</h4>
<p class="category">category text</p>
</div>
<div class="content">
<!-- The fileinput-button span is used to style the file input field as button -->
<span class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Select files...</span>
<!-- The file input field used as target for the file upload widget -->
<input id="fileupload" type="file" name="files[]" multiple>
</span>
<br>
<br>
<!-- The global progress bar -->
<div id="progress" class="progress">
<div class="progress-bar progress-bar-success"></div>
</div>
<!-- The container for the uploaded files -->
<div id="files" class="files"></div>
</div>
<div class="footer">
<hr>
<div class="stats">
<i class="fa fa-history"></i> footer
</div>
</div>
</div>
</div>
</div>
<script>
/*jslint unparam: true */
/*global window, $ */
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = '/sessions/import';
$('#fileupload').fileupload({
url: url,
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo('#files');
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
},
success: function(response) {
var json = $.parseJSON(response);
alert(json['message']);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
</script>
In my controller I have:
public function import()
{
if ($this->request->is('post')) {
$options = array(
'max_file_size' => 2048000,
'max_number_of_files' => 10,
'access_control_allow_methods' => array(
'POST'
),
'accept_file_types' => '/\.(png|jpg)$/i',
'upload_dir' => '../uploads/workbench/', //WWW_ROOT . 'files' . DS . 'uploads' . DS,
'upload_url' => '/files/uploads/',
'print_response' => false
);
$result = $this->JqueryFileUpload->upload($options);
print_r($result);
die();
}
}
Solved. It was something to do with me using a proxy. When I removed the proxy it worked fine. No idea why that happens though.

Categories