Dropzone.js call a custom function after file is uploaded - javascript

I want to call my own function after the file/files successfully uploaded. This is what I have done so far. Files are being uploaded without a problem but the following code is not working actually.
I just put this code above the Dropzone upload form..
<script>
$(function() {
Dropzone.options.dropzoneJsForm = {
maxFilesize: 10, // Mb
init: function () {
this.on('completemultiple', function () {
alert("sdfsdf");
});
}
};
});
</script>

Add "uploadMultiple: true" to your init.
$(function() {
Dropzone.options.dropzoneJsForm = {
maxFilesize: 10, // Mb
uploadMultiple : true,
init: function () {
this.on('completemultiple', function () {
alert("sdfsdf");
});
}
};
});

Related

Reset FilePond Input in Javascript

I have implemented Filepond uploaded in my page. When the user selects a file, I set that file on a html canvas for edits. However when the user wants to upload another file, filepond input retains last uploaded file.
I have tried FilePond.destroy(inputElement); after the file is successfully set on the canvas in the FilePond:addfile event.
$('.upload-file').filepond();
$.fn.filepond.registerPlugin(
FilePondPluginFileValidateType,
FilePondPluginFileValidateSize,
FilePondPluginImageResize,
FilePondPluginImageExifOrientation,
FilePondPluginImagePreview,
FilePondPluginImageTransform,
FilePondPluginImageCrop,
FilePondPluginImageValidateSize,
);
FilePond.setOptions({
labelIdle: 'Drag & Drop your file or <span class="filepond--label-
action"> Browse </span>',
maxFiles: 1,
allowDrop: true,
allowMultiple: false,
dropOnPage: true, //for page to work, element has to be false https://github.com/pqina/filepond/issues/113
dropOnElement: false,
labelTapToCancel: '', //we dont want to allow cancel
labelTapToUndo: '',
maxFileSize: intFileSizeInMB,
allowReplace: true,
allowRevert: false,
instantUpload: false
});
const pond = document.querySelector('.filepond--root');
pond.addEventListener('FilePond:addfile', e => {
console.log('File added', e.detail);
if (e.detail) {
if (e.detail.file && e.detail.file.file.name) {
SetFileOnCanvas(e.detail.file.file, e.detail.file.file.name);
const inputElement = document.querySelector('input[type="file"]');
FilePond.destroy(inputElement);
}
}
});
pond.addEventListener('FilePond:processfile', e => {
console.log('Process File COMPLETE', e.detail);
});
After a file is uploaded and set to Canvas the file upload input should be cleared and ready for another upload.
Working solution
var pond_ids = [];
if (pond.getFiles().length != 0) { // "pond" is an object, created by FilePond.create
pond.getFiles().forEach(function(file) {
pond_ids.push(file.id);
});
}
pond.removeFiles(pond_ids);
After upload file "Complete function"
you can do like this (simple example):
if (filePond.getFiles().length != 0) {
for (var i = 0; i <= filePond.getFiles().length - 1; i++) {
filePond.removeFile(filePond.getFiles()[0].id)
}
}
I know its too late but you can use
let filePond = FilePond.find(document.getElementById(filePondElementId));
if (filePond != null) {
//this will remove all files
filePond.removeFiles();
}
<script src="https://unpkg.com/filepond/dist/filepond.min.js"></script>
Assuming that you create your filepond instance through function create_pondProfile and your input has class filepond, in you filepond config in server block do like this:
server: {
url: '',
process: {
url: '/path/to/upload/',
headers: {'X-CSRF-TOKEN': csrf},
ondata: (formData) => {
return formData;
},
onload: (response) => {
FilePond.destroy(document.querySelector('.filepond'));
create_pondProfile('.filepond');
}
},
...
...
}
It will destroy current instance of filepond and creates new one after upload.

Cordova File API saving file to memory card

Firstly why in gods name is there no tutorial for this even Cordova's guides don't tell you how to save a flaming file to a location on the phone.
(function(w){
function FileServices(FileName, callb){
var self = this;
var isFileOpen = false;
var fileHandler;
// open file handle
function OpenFile(callb){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 5*1024, function (fs) {
fs.root.getFile(cordova.file.externalDataDirectory+FileName, { create: true, exclusive: false }, function (fileEntry) {
fileHandler = fileEntry;
isFileOpen = true;
callb(self, fileHandler);
});
}, function(e,c){console.log(e,c);});
}
// write to file
function WriteFile(fileEntry, dataObj, isAppend, callback) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function (fileWriter) {
fileWriter.onerror = function (e) {
};
// If we are appending data to file, go to the end of the file.
if (isAppend) {
try {
fileWriter.seek(fileWriter.length);
}
catch (e) { }
}
fileWriter.write(dataObj);
callback(self, fileWriter);
});
}
this.writeLine = function(txt, append, callback){
if(isFileOpen){
WriteFile(fileHandler, new Blob([txt], { data:'plain/text' }), append, callback);
}
}
OpenFile(callb);
};
// add to the navigator when device ready
document.addEventListener("deviceready", function(){
navigator.FileServices = function GetFileServices(FileName, callback){
return new FileServices(FileName, callback);
}
});
})(window);
All i get is "Error Code 5 = FileError.ENCODING_ERR";
I can't work it out....

Image preview script breaks on uploading the same image that was previously deleted

I am using this package, and I have modified it a bit, so that I can upload, drag and sort the images and preview them in the browser. Uploading works fine, and deleting of images. But I found a scenario when the script breaks. When I have more than one image and I delete the first image, on trying to upload the same image that I deleted the script doesn't work anymore. But if I don't try to upload the same image immediately and first upload some other and then the one that was deleted, then it works. Also, I don't get any errors in the console. I am not sure how to fix this.
My full code is here.
This is part of the code:
$(document).ready(function () {
var imageCounter = 0;
$('#articleForm').submit(function () {
uploadPosition();
});
function uploadPosition() {
var uploadedImagesPositions = [];
$.each($('.jFiler-item-thumb-image'), function (index, value) {
$(this).attr('data-position-index', index);
uploadedImagesPositions[index] = $(this).find('img').attr('src');
});
if (!$('input[name="uploadedItems"]').length) {
$('<input>', {
type: "hidden",
name: "uploadedItems"
}).appendTo('#articleForm')
}
$('input[name="uploadedItems"]').val(JSON.stringify(uploadedImagesPositions));
$("input[name^='jfiler-items-exclude-']:hidden").detach();
console.log(uploadedImagesPositions);
}
$('#upload').filer({
limit: null,
maxSize: null,
extensions: null,
changeInput: '<div class="jFiler-input-dragDrop"><h1>+</h1></div>',
showThumbs: true,
appendTo: '.uploaded_items',
theme: "default",
templates: {
box: '<div class="jFiler-item-list"></div>',
item: '<div class="jFiler-item img-container dragdiv"></div>',
itemAppend: '<div class="jFiler-item img-container dragdiv"></div>',
progressBar: '<div class="bar"></div>',
itemAppendToEnd: false,
removeConfirmation: false,
_selectors: {
list: '.jFiler-item-list',
item: '.jFiler-item',
progressBar: '.bar',
remove: '.jFiler-item-trash-action',
}
},
uploadFile: {
url: "/admin/articles/ajax",
data: {
'_token': $('input[name="_token"]').val()
},
type: 'POST',
enctype: 'multipart/form-data',
beforeSend: function () {},
success: function (data, el) {
uploadedImagesPositions = [];
console.log(data);
var filenameArray = data.split('/');
var name = filenameArray.slice(-1).pop();
var filename = name.replace(/[\/\s()]/g, '');
var imageContainer = $('[data-jfiler-index="' + imageCounter + '"]').first();
$('<div class="jFiler-item-thumb-image"><img src="/imagecache/thumb/' + filename + '"></div><div class="overlay"><span><i class="jFiler-item-trash-action ion-trash-a"></span></div>').appendTo(imageContainer);
imageCounter++;
$(".dragdiv").each(function () {
makeElementAsDragAndDrop($(this));
});
$('.images-refresh').hide();
$('.images-refresh').click(function () {
$(this).closest("form").submit()
});
function makeElementAsDragAndDrop(elem) {
$(elem).draggable({
revert: "invalid",
cursor: "move",
helper: "clone"
});
$(elem).droppable({
activeClass: "ui-state-hover",
hoverClass: "ui-state-active",
drop: function (event, ui) {
uploadedImagesPositions = [];
$('.images-form a').hide();
$('.images-refresh').show();
var $dragElem = $(ui.draggable).clone().replaceAll(this);
$(this).replaceAll(ui.draggable);
makeElementAsDragAndDrop(this);
makeElementAsDragAndDrop($dragElem);
}
});
}
var parent = el.find(".jFiler-jProgressBar").parent();
el.find(".jFiler-jProgressBar").fadeOut("slow", function () {
$("<div class=\"jFiler-item-others text-success\"><i class=\"icon-jfi-check-circle\"></i> Success</div>").hide().appendTo(parent).fadeIn("slow");
});
},
error: function (el) {
console.log(el);
var parent = el.find(".jFiler-jProgressBar").parent();
el.find(".jFiler-jProgressBar").fadeOut("slow", function () {
$("<div class=\"jFiler-item-others text-error\"><i class=\"icon-jfi-minus-circle\"></i> Error</div>").hide().appendTo(parent).fadeIn("slow");
});
},
statusCode: {},
onProgress: function () {},
},
dragDrop: {
dragEnter: function () {},
dragLeave: function () {},
drop: function () {},
},
addMore: true,
clipBoardPaste: true,
excludeName: null,
beforeShow: function () {
return true
},
onSelect: function () {},
afterShow: function () {},
onRemove: function (el) {
imageCounter = $('.img-container').size() - 1;
//uploadPosition();
//console.log(el.find('img').attr('src'));
},
onEmpty: function () {
imageCounter = 0;
},
captions: {
button: "Choose Files",
feedback: "Choose files To Upload",
feedback2: "files were chosen",
drop: "Drop file here to Upload",
removeConfirmation: "Are you sure you want to remove this file?",
errors: {
filesLimit: "Only {{fi-limit}} files are allowed to be uploaded.",
filesType: "Only Images are allowed to be uploaded.",
filesSize: "{{fi-name}} is too large! Please upload file up to {{fi-maxSize}} MB.",
filesSizeAll: "Files you've choosed are too large! Please upload files up to {{fi-maxSize}} MB."
}
}
});
});
Update
I have updated fiddle with HTML and CSS as well as javascript code, unfortunately, I couldn't get it to work, so not sure how helpful it is, but at least you can see the full code.
I am using this scripts on my page where I upload images:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js" integrity="sha384-I6F5OKECLVtK/BL+8iSLDEHowSAfUo76ZL9+kGAgTRdiByINKJaqTPH/QVNS1VDb" crossorigin="anonymous"></script>
<script type="text/javascript" src="{{ asset('js/foundation/foundation.min.js') }}"></script>
<script>$(document).foundation();</script>
<script type="text/javascript" src="{{ asset('js/jquery-ui/jquery-ui.min.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/jquery-filer/jquery-filer.js') }}"></script>
jquery-filer is the script that I use for upload, the one that I have in fiddle.
And this is my server-side function for ajax upload. I am using PHP laravel in the backend:
public function ajaxUpload() {
if (Input::hasFile('file')) {
$files = Input::file('file');
foreach ($files as $file) {
$time = microtime(true);
$name = $file->getClientOriginalName();
$filename = $time.'-'.preg_replace('/[(\)\s]/u', '', $name);
if(substr($file->getMimeType(), 0, 5) == 'image') {
try {
$original = Image::make($file)->save(public_path($this->destinationPath.'/'.$filename));
\Log::info('try: '.$filename."\n");
} catch (Exception $e) {
\Log::info('Caught exception: '.$e->getMessage(). "\n");
}
$img = Image::cache(function($image) use ($original){
return $image->make($original);
});
}
}
}
return $this->destinationPath.$filename;
}
I have tried to salvage the problem part in your code and came up with this (Fiddle).
The problem part is probably in the success function. Instead of trying to get element by its index, use the 2nd argument passed to the success function.
success: function(data, el) {
uploadedImagesPositions = [];
var filenameArray = data.split('/');
var name = filenameArray.slice(-1).pop();
var filename = name.replace(/[\/\s()]/g, '');
// Instead of this
// var imageContainer = $('[data-jfiler-index="' + imageCounter + '"]').first();
// Use this
var imageContainer = el;
$('<div class="jFiler-item-thumb-image"><img src="/imagecache/thumb/' + filename + '"></div><div class="overlay"><span><i class="jFiler-item-trash-action ion-trash-a"></span></div>').appendTo(imageContainer );
}
The problem could also be caused by your server side, which we have no access right now.
Try to update to https://innostudio.de/fileuploader/ (jQuery.filer was transfered to the Fileuploader)
I was also using a JS image uploader which has the same type of issue. When a user uploads an image and deletes it and uploads the same image again, it does not work.
So I fixed it using:
$('input[type="file"]').val(null);
in the image deleted event.

Gallery using Photobox

I am using the following code for a gallery in AngularJS but if I try to use it without AngularJS it doesn't seems to work. If I run it with AngularJS then it will open the images properly but if I run it normally it will open the image as Can anyone to explain to me the difference?
app.js (AngularJS)
app.controller('GalleryController', function() {
var gallery = $('#gallery'),
gallery1 = $('#gallery1');
console.log("init gallery");
$('#gallery').photobox('a', {
thumbs: true,
loop: false
}, callback);
$('#gallery1').photobox('a', {
thumbs: true,
loop: false
}, callback);
function callback(){
console.log('image has been loaded');
}
console.log("GALLERY CONTROLLER BEGIN");
});
gallery.html (jQuery)
(function() {
'use strict';
var gallery = $('#gallery'),
gallery1 = $('#gallery1');
console.log("init gallery");
$('#gallery').photobox('a', {
thumbs: true,
loop: false
}, callback);
$('#gallery1').photobox('a', {
thumbs: true,
loop: false
}, callback);
function callback(){
console.log('image has been loaded');
}
console.log("GALLERY CONTROLLER BEGIN");
});

Valums qq.FileUploader doesn't work when it's initialized after loading button by ajax

I use Valums qq.FileUploader(ex-AjaxUpload) plugin for uploading in my Asp.net mvc 3 application...
I have some button in my page add-newimage, and by clicking in it I get modal window, and I load data into that window by loading Partial View.
And in that partial view I have button upload-image , in which I want to initilaize my qq.FileUploader, but it doesn't work anywhere...
Here is code
$("#add-newimage").click(function () {
$("#add-image").load('/Design/AddImage/', function () {
$("#add-image").dialog('open');
var uploader= new qq.FileUploader({
element: document.getElementById("upload-image"),
action: '/Design/UploadImage',
allowedExtensions: ['jpg'],
onComplete: function (id, fileName, responseJSON) {
$("#hidden-path input").html("/Img/Temp/#User.Identity.Name/" + file);
alert($("#hidden-path input").html());
}
});
});
});
How can I make it work?
I would try to put the uploader code in the open event of your dialog.
$("#add-image").dialog({
open : function(event, ui) {
var uploader= new qq.FileUploader({
element: document.getElementById("upload-image"),
action: '/Design/UploadImage',
allowedExtensions: ['jpg'],
onComplete: function (id, fileName, responseJSON) {
$("#hidden-path input").html("/Img/Temp/#User.Identity.Name/" + file);
alert($("#hidden-path input").html());
}
}
});
..
$("#add-newimage").click(function () {
$("#add-image").load('/Design/AddImage/', function () {
$("#add-image").dialog('open');
});
});

Categories

Resources