How to programatically update dropzone preview filename after using fileRename option - dropzone.js

I have a DropZone script (as below) that renames the uploaded image into a unique folder with a unique timestamp to avoid duplicates. When I add the file, it creates the unique directory (session_id) and uploads and renames the image correctly, however, the DropZone preview image still shows the original filename so the remove links do not work. If I refresh the page, the thumbnails are labelled correctly with the new filename and the remove links work. How can I update the script to do this after the initial upload/rename?
Dropzone.autoDiscover = false;
$(".dropzone").dropzone({
url: "upload.php",
addRemoveLinks: true,
maxFiles: 5,
acceptedFiles: "image/*",
// Check for previously uploaded images and display in the dropzone
init: function() {
myDropzone = this;
$.ajax({
url: 'upload.php',
type: 'post',
data: {request: 2},
dataType: 'json',
success: function(response) {
$.each(response, function(key,value){
var mockFile = { name: value.name, size: value.size };
myDropzone.emit("addedfile", mockFile);
myDropzone.emit("thumbnail", mockFile, value.path);
myDropzone.emit("complete", mockFile);
});
}
});
},
// Rename uploaded files to unique name
renameFile: function (file) {
let newName = new Date().getTime() + '_' + file.name;
return newName;
},
// Remove the uploaded file if the "Remove file" link is pressed
removedfile: function(file) {
var name = file.name;
$.ajax({
type: 'post',
url: 'delete.php',
data: "id="+name,
dataType: 'html'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
},
});
This is the upload.php file:
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/inc/config.inc.php';
$upload_folder = "uploads/".session_id();
if(!file_exists($upload_folder)) {
mkdir($upload_folder);
}
$target_dir = $upload_folder."/";
$request = 1;
if(isset($_POST['request'])){
$request = $_POST['request'];
}
// Upload file
if($request == 1){
$target_file = $target_dir . basename($_FILES["file"]["name"]);
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo $target_file;
}else{
echo 0;
}
die;
}
// Read files from
if($request == 2){
$file_list = array();
// Target directory
$dir = $target_dir;
if (is_dir($dir)){
if ($dh = opendir($dir)){
// Read files
while (($file = readdir($dh)) !== false){
if($file != '' && $file != '.' && $file != '..'){
// File path
$file_path = $target_dir.$file;
// Check its not folder
if(!is_dir($file_path)){
$size = filesize($file_path);
$file_list[] = array('name'=>$file,'size'=>$size,'path'=>$file_path);
}
}
}
closedir($dh);
}
}
echo json_encode($file_list);
exit;
}
?>
This is the delete.php file:
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/inc/config.inc.php';
$upload_folder = "uploads/".session_id();
$target_dir = $upload_folder."/";
if(isset($_POST['id'])){
$filename = $_POST['id'];
}
// Delete file
$target_file = $target_dir . $filename;
if (unlink($target_file)) {
echo $target_file;
}else{
echo 0;
}
die;
?>
(NOTE: session_start() is called in the included config file)
Feel free to let me know if there are any other bad ideas in here! :)
Ben

So the answer for this has been solved! For reference the following is the fixes applied.
renameFile: and removedfile: have both been updated as per the comments below.
The changes in the renameFile: section make the newly generated filename available to be referenced later when using the removedfile: Ajax call to delete.php
The init: > success: has been updated changing the mockFile variable.
This ensures that removefile: still works correctly on a page reload (e.g. is there was a form POST and an error needed to be corrected) where the images are now read directly from the folder location.
Full code update:
Dropzone.autoDiscover = false;
$(".dropzone").dropzone({
url: "upload.php",
dictDefaultMessage: "", // remove default text
addRemoveLinks: true,
maxFiles: 5,
acceptedFiles: "image/*",
// Check for previously uploaded images and display in the dropzone
init: function() {
myDropzone = this;
$.ajax({
url: 'upload.php',
type: 'post',
data: {request: 2},
dataType: 'json',
success: function(response) {
$.each(response, function(key,value){
var mockFile = {
newName: value.name,
name: value.name.substr(value.name.indexOf('_') + 1),
size: value.size
};
myDropzone.emit("addedfile", mockFile);
myDropzone.emit("thumbnail", mockFile, value.path);
myDropzone.emit("complete", mockFile);
});
}
});
},
// Rename uploaded files to unique name
renameFile: function (file) {
let newName = new Date().getTime() + '_' + file.name;
// Add new name to the file object:
file.newName = newName;
// As an object is handed over by reference it will persist
return newName;
},
// Remove the uploaded file if the "Remove file" link is pressed
removedfile: function(file) {
// Get new name from file object:
var newName = file.newName;
$.ajax({
type: 'post',
url: 'delete.php',
data: "id="+newName,
dataType: 'html'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
},
});
Thanks to the user "Sempervivum" on webdeveloper.com for the fix.

Related

Dropzone.js - remove preview file if upload fails

I have a problem with my dropzone,
$(".js-example-basic-multiple").select2();
Dropzone.options.dropZone = {
//options here
maxFilesize: 2,
addRemoveLinks: true,
removedfile: function(file) {
var name = file.name;
$.ajax({
type: 'POST',
url: host+'upload/unfile',
data: "id="+name,
dataType: 'html'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
//console.log();
},
init: function() {
this.on("maxfilesexceeded", function(file){
alert("No more files please!");
});
}
}
My problem is, when a file fails to upload, it still shows the preview images, so i need that file to be removed automatically when these file fails to upload, how can I do that??
I think, if I understand you correctly, you can just delete the image with this code:
Dropzone.options.dropZone = {
...
, error: function(file, message, xhr) {
$(file.previewElement).remove();
},
...
}
Just read the documentation again.
This code is from the docs:
myDropzone.on("error", function(file) {
myDropzone.removeFile(file);
});
Please let me know, if it works in your case.
When connect error is "xhr.ontimeout", function "error:" don't run.
I need (paste next to "init:"):
sending: function(file, xhr, formData) {
//Execute on case of timeout only
xhr.ontimeout = function(e) {
alert('connection interrupted');
};
}

Ajax returned title value for tooltip isn't in one line, in Bootstrap

I am having a weird bug with dynamic created tooltips using ajax. I am creating a simple notes function. When data is coming from the database everything looks nice
But when i am creating a new note, using ajax i am creating the new entry in the db and then return the value to be shown in the new tooltip...But this is how it comes out to the user.
Is there a way to 'force' it to one line like the 1st image ?
Here is the code in question:
.js part
$('[data-toggle="tooltip"]').tooltip({
placement : 'left'
});
////////
var inText = $('.evnt-input').val(); //Whatever the user typed
$.ajax({
type: 'POST',
url: 'request.php',
data: {action:'addnotes', data: inText},
dataType: 'json',
success: function(s){
if(s.status == 'success'){
$('<li id="'+s.id+'">' + inText + ' ✕ </li>').appendTo('.event-list');
}
},
error: function(e)
{
console.log('error');
}
});
.php part
if ($_POST["action"] == "addnotes"){
function addnotes($data)
{
$insert = db_query("insert into notes(description) values('$data')");
if($insert)
return db_inserted_id();
}
$data = $_POST['data'];
$status = addnotes($data);
if($status != ''){
$timestamp = strtotime(date('Y-m-d G:i:s'));
$curTime = date( 'F j, Y, g:i a', $timestamp );
$output = array('status'=>'success','id'=>$status, 'curTime'=>$curTime);
}
else
$output = array('status'=>'error');
echo json_encode($output);
}
I have an identical code with the .js part to show the notes when the page loads...of course that works fine.
Lol it was so easy.... I changed the .js part to this, to 'reinitialize' the tooptip:
if(s.status == 'success'){
var curTime = s.curTime;
$('<li id="'+s.id+'">' + inText + ' ✕ </li>').appendTo('.event-list');
$('[data-toggle="tooltip"]').tooltip({
placement : 'left'
});
}

Parse.User.current() returns null

We are trying to create a file upload system. We currently have a form in upload.ejs that allows the user to select a file and then the form calls upload.js which uses Parse's REST API to upload the file. In the success field of the REST API we are saving information about the file uploaded to our parse database. We would also like to save the information about the user uploading the file, but Parse.User.current() is returning null.
Our upload.js is saved in the public folder and the code is as follows:
$(function() {
var file;
$('#fileselect').bind("change", function(e) {
var files = e.target.files || e.dataTransfer.files;
// Our file var now holds the selected file
file = files[0];
});
$('#uploadbutton').click(function() {
var serverUrl = 'https://api.parse.com/1/files/' + file.name;
$.ajax({
type: "POST",
beforeSend: function(request) {
request.setRequestHeader("X-Parse-Application-Id", 'YOUR-APPLICATION-ID');
request.setRequestHeader("X-Parse-REST-API-Key", 'YOUR-REST-API-KEY');
request.setRequestHeader("Content-Type", file.type);
},
url: serverUrl,
data: file,
processData: false,
contentType: false,
success: function(data) {
//alert("File available at: " + data.url);
var Note = Parse.Object.extend("Note");
var note = new Note();
note.set("File Name", file.name); //change to user inputted file name
note.set("url", data.url);
//note.set("uploader", Parse.User.current());
console.log(Parse.User.current());
note.save();
var success = "<p>File Successfully Added. View it by clicking <a target='_blank' href="+data.url+">Here</a></p>";
$("#uploadMessage").addClass("uploadPadding");
$('#uploadMessage').append(success);
//TO DO: redirect off page
},
error: function(data) {
var obj = jQuery.parseJSON(data);
alert(obj.error);
}
});
});
});

Angularjs upload service with onLoad image?

i have some issues with onload image and angular-fie-upload. first, i have to validate an image size after that i will upload this image to server side with the following code. my service look like that :
Services.factory('$uploadWrapper', ['$upload' , '$logger' , function ($upload, $logger) {
return function (url, file, informations, onSuccess, onError, onProgress) {
url = url || angular.noop;
file = file || angular.noop;
informations = informations || angular.noop;
onSuccess = onSuccess || angular.noop;
onError = onError || angular.noop;
onProgress = onProgress || angular.noop;
$upload.upload({
url: url,
method: 'POST',
// headers: {'header-key': 'header-value'},
// withCredentials: true,
data: informations,
file: file // or list of files: $files for html5 only
/* set the file formData name ('Content-Desposition'). Default is 'file' */
//fileFormDataName: myFile, //or a list of names for multiple files (html5).
/* customize how data is added to formData. See #40#issuecomment-28612000 for sample code */
//formDataAppender: function(formData, key, val){}
}).progress(function (evt) {
$logger.info(Math.min(100, parseInt(100.0 * evt.loaded / evt.total)));
onProgress(evt);
}).success(function (response) {
$logger.info('POST' + url + angular.toJson(response))
onSuccess(response);
}).error(function (error) {
$logger.error('POST' + url + ' ' + angular.toJson(error));
onError(error);
});
}
}]);
and for validation process, i will create an image to take the width and the height of my image :
$scope.onFileSelect = function ($files) {
$scope.loading = true;
//$files: an array of files selected, each file has name, size, and type.
file = $files[0];
var img = new Image();
img.src = _URL.createObjectURL(file);
img.onload = function () {
console.log(this.width + "x" + this.height);
if (img.width > sizes.width && img.height > sizes.height) {
$uploadWrapper(pinholeAdminServerRoutes.image.upload, file, {
"operationType": 'channels',
"objectId": $scope.channel.id,
"size": 'large'
}, function (response) {
$scope.loading = false;
}, function (error) {
$scope.errors.push(error);
$scope.loading = false;
});
} else {
$scope.imageSizeNotValid = true;
$scope.loading = false;
}
console.log('finish loading');
};
};
but, my service won't work inside the onload block. but the same service will work without the onload block.
i finally got a solution by using $scope.$apply inside the onload event.

How to upload image using ajax and zend?

Thank you for the consideration, I'm sorry for my non-informative question.
Actually I am using ajax and zend for uploading a file.
My ajax code looks like this:
$.ajax({
type: "POST",
url: "/business_general/imagesave",
enctype: 'multipart/form-data',
data: {'file': files.getAsBinary(), 'fname' : file.fileName},
success: function(arrReturn){
alert( "Data Uploaded: ");
}
});
Here, I called a controller action(imagesave) to save my image in database
My Controller file action looks like this:
$config = Zend_Registry::get('config');
$vehiclelogo = $config->paths->vehiclelogo;
$file = $objRequest->getParam('file');
$ret = $objRequest->getParam('fname');
$path_parts = pathinfo($ret);
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n";
$targetPath = mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y"));
try {
echo "POSTED FILE NAME"." ". $ret;
echo "TYPE OF FILE UPLOADED"." "."-". gettype($ret);
$strFilePath = $vehiclelogo.'/'.$targetPath.'.'.$path_parts['extension'];
$OPfile = fopen($strFilePath,"w");
fwrite($OPfile,$file);
fclose($OPfile);
echo "completed";
}
catch (Exception $e) {
echo "error";
}
Here, I am uploading the selected image into a folder.Acually, I am able to upload text files. But if I upload png/jpeg files,it gets uploaded into the folder, But the fact is that it could not be opened.
I should be able to able to upload every type of files.
How to execute this in zend-php and ajax?
Sorry .I think getAsBinary() doesn't support in modern browsers.you can use an invisible canvas for uploding files using ajax.
Example
var canvas = document.getElementById("canvas")
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img,0,0);
var strdata = canvas.toDataURL("image/png");
document.getElementById("company_logo").src=strdata;
$.ajax({
type: "POST",
url: "/business_vehicle/vehiclegeneralsave",
data: "&data="+strdata,
success: function(arrResult) {
//do something
}
});
In controller side you can recive the image ` public function vehiclegeneralsaveAction() {
$file = $arrVehicleDetails = trim($objRequest->getParam('data'));
$strEncodedData = str_replace(' ', '+', $file);
$strFilteredData = explode(',', $strEncodedData);
$strUnencoded = base64_decode($strFilteredData[1]);
file_put_contents('../public/image/image.png', $strUnencoded);
}`

Resources