Enable copy and paste files in dropzone.js - javascript

I am using dropzone.js. I want to implement the "Copy & Paste" feature in it.
What I tried is:
Inside dropzone.js:
paste: function(e) {
Dropzone.prototype.emit("paste");
}
Dropzone.prototype.paste = function(e) {
var items, _ref;
if ((e != null ? (_ref = e.clipboardData) != null ? _ref.items : void 0 : void 0) == null) {
return;
}
this.emit("paste", e);
items = e.clipboardData.items;
if (items.length) {
return this._addFilesFromItems(items);
}
};
Page level script:
<script>
var dropZone = Dropzone.forElement('#dropzone1');
dropZone.paste();
</script>
The above is not calling paste:function(e){..}
How to rectify it?

If you don't want to use other JS libraries, you can integrate dropzone with a paste event fairly easily by retrieving the data as a file from the paste event:
// create dropzone however you wish
const myDropzone = new Dropzone("div#element", { url: "/path/to/upload"});
// add paste event listener to the page
document.onpaste = function(event){
const items = (event.clipboardData || event.originalEvent.clipboardData).items;
items.forEach((item) => {
if (item.kind === 'file') {
// adds the file to your dropzone instance
myDropzone.addFile(item.getAsFile())
}
})
}

This worked for me. It uses the FileReaderJS wrapper.
As I am not creating the dropzone programatically, I had to store it at runtime with the init() method.
See here for the FileReaderJS part.
var myDropzone;
function checkUploadFile(filename) {
//do some input checking here, if you want
return true;
}
Dropzone.options.FileDropUploadZone = {
paramName: "myDiv",
maxFilesize: 3, // MB
uploadMultiple: true,
addRemoveLinks: true,
acceptedFiles: 'image/*',
maxFiles: 10,
accept: function(file, done) {
if (!checkUploadFile(file.name)) {
done('Invalid file');
myDropzone.removeFile(file);
}
else { done(); }
},
init: function() {
myDropzone = this;
}
};
$(document).ready(function () {
FileReaderJS.setupClipboard(document.body, {
accept: {
'image/*': 'DataURL'
},
on: {
load: function(e, file) {
myDropzone.addFile(file);
}
}
});
});

var myDropzone = new Dropzone(".dropzone", { });
document.onpaste = function(event){
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
for (index in items) {
var item = items[index];
if (item.kind === 'file') {
// adds the file to your dropzone instance
myDropzone.addFile(item.getAsFile())
}
}
}
Just add this code. Do not declare URL because URL also declared in PHP or coding file, paste this code in view file (HTML, PHP, etc).

Related

Quill.js add a custom javascript function into the editor

I am using Quill.js to have users create custom user designed pages off the main web page. I have a custom slider that I have written in javascript that will take images and rotate through them. I have the toolbar in quill setup to be able to click on the toolbar to setup the slider in a modal window.
When the user clicks to close the modal slider setup window, I'm trying to insert an edit button in the html editor where the cursor sits so the user can edit the information that was just entered or possible delete the button by removing all the information in the slider modal window.
I have written custom blots, followed all the examples I could find and nothing worked. I did get a custom html tag to show, but not a button. When I requested the html from quill when I setup the custom html tag in the editor, all I get is "" from quill.root.innerHTML none of the custom tag or the information in it even though I see it correctly in the editor.
I would like a button in the editor to make it easy to edit the slider data, as there could be more than one. I am not going to limit the number of sliders. It is up to the user to ruin their own page.
I will not be rendering the slider in the edit html window, just trying to display a button to click on. I do give the user a preview button on the modal window to view the slider if they so choose.
I also would like to store the setup information of the slider in a data tag in json format in the button and change that html button to a tag along with the json data when rendering the html in the browser window.
Can this be done in Quill.js?
I did this by using the import blots embed. I don't register as a button but clicking on the blot I do get a link to the embedded data and trigger the edit of the carousel data on that click.
var Quill;
const BlockEmbed = Quill.import("blots/block/embed");
const Link = Quill.import('formats/link');
class Carousel extends BlockEmbed {
static create(value) {
var self = this;
const node = super.create(value);
node.dataset.carousel = JSON.stringify(value);
value.file.frames.forEach(frame => {
const frameDiv = document.createElement("div");
frameDiv.innerText = frame.title;
frameDiv.className += "previewDiv";
node.appendChild(frameDiv);
});
node.onclick = function () {
if (Carousel.onClick) {
Carousel.onClick(self, node);
}
};
return node;
}
static value(domNode) {
return JSON.parse(domNode.dataset.carousel);
}
static onClick: any;
static blotName = "carousel";
static className = "ql-carousel";
static tagName = "DIV";
}
Quill.register("formats/carousel", Carousel);
I then include this as a script on the page where quill is editing the HTML
<script src="~/js/quilljs-carousel.js"></script>
And then this is the custom javascript to handle the events of the blot displayed in a custom modal dialog in a hidden div tag
<script>
function CarouselClicked(blot, node) {
editCarousel(JSON.parse(node.dataset.carousel), node);
}
var Carousel = Quill.import("formats/carousel");
Carousel.onClick = CarouselClicked;
function carouselToolbarClickHandler() {
createCarousel();
}
var Toolbar = Quill.import("modules/toolbar");
Toolbar.DEFAULTS.handlers.carousel = carouselToolbarClickHandler;
$(document).ready(function() {
var div = $("#editor-container");
var Image = Quill.import('formats/image');
Image.className = "img-fluid";
Quill.register(Image, true);
var quill = new Quill(div.get(0),
{
modules: {
syntax: true,
toolbar: '#toolbar-container'
},
theme: 'snow'
});
div.data('quill', quill);
// Only show the toolbar when quill is ready to go
$('#toolbar-container').css('display', 'block');
div.css('display', 'block');
$('#editor-loading').css('display', 'none');
// Override the quill Image handler and create our own.
quill.getModule("toolbar").addHandler("image", imageHandler);
});
function createCarousel() {
$("#carouselModalForm").removeClass("was-validated").get(0).reset();
$("#carouselModalList").empty();
$("#carouselModal")
.data("state", "unsaved")
.one("hidden.bs.modal",
function() {
var data = getCarouselData();
var carouselData = {};
carouselData['file'] = data;
carouselData['speed'] = $('#time').val();
carouselData['height'] = $('#height').val();
carouselData['width'] = $('#width').val();
var quill = $("#editor-container").data().quill;
var range = quill.getSelection(true);
if (range != null) {
quill.insertEmbed(
range.index,
"carousel",
carouselData,
Quill.sources.USER
);
quill.setSelection(range.index + 2, Quill.sources.USER);
}
})
.modal("show");
$('#title').get(0).outerText = "Create Carousel";
}
function editCarousel(value, node) {
$("#carouselModalForm").get(0).reset();
var elem = $("#carouselModalList").empty();
$.each(value.file.frames,
function(i, data) {
$("<option>").appendTo(elem).text(data.title).data("frame", data);
});
$('#time').val(value.speed);
$('#height').val(value.height);
$('#width').val(value.width);
var modal = $("#carouselModal");
modal.find("form").removeClass("was-validated");
modal
.data("state", "unsaved")
.one("hidden.bs.modal",
function() {
if ($("#carouselModal").data("state") !== "saved")
return;
var data = getCarouselData();
var carouselData = {};
carouselData['file'] = data;
carouselData['speed'] = $('#time').val();
carouselData['height'] = $('#height').val();
carouselData['width'] = $('#width').val();
var carousel = Quill.find(node, true);
carousel.replaceWith("carousel", carouselData);
})
.modal("show");
$('#title').get(0).outerText = "Edit Carousel";
}
function getCarouselData() {
var options = $("#carouselModalList").find("option");
var frames = $.map(options,
function(domNode) {
return $(domNode).data("frame");
});
return {
frames : frames
};
}
function getCarouselFrameFormData() {
// Get data from frame
function objectifyForm(formArray) { //serialize data function
var returnArray = {};
for (var i = 0; i < formArray.length; i++) {
returnArray[formArray[i]['name']] = formArray[i]['value'];
}
return returnArray;
}
return objectifyForm($("#carouselFrameModalForm").serializeArray());
}
$("#carouselModalNewFrame").click(function() {
$("#carouselFrameModalForm").removeClass("was-validated").get(0).reset();
$("#backgroundPreview").attr("src", "");
$("#mainPreview").attr("src", "");
$("#carouselFrameModal")
.data("state", "unsaved")
.one("hidden.bs.modal",
function() {
if ($("#carouselFrameModal").data("state") == "saved") {
var data = getCarouselFrameFormData();
$("<option>").appendTo($("#carouselModalList")).text(data.title).data("frame", data);
}
})
.modal("show");
// Fetch all the forms we want to apply custom Bootstrap validation styles to
});
$("#carouselModalEditFrame").click(function () {
var form = $("#carouselFrameModalForm");
form.removeClass("was-validated").get(0).reset();
var selected = $("#carouselModalList option:selected");
var frame = selected.data("frame");
$.each(Object.keys(frame),
function (i, e) {
$("input[name=" + e + "]", form).val(frame[e]);
});
$("#backgroundPreview").attr("src", frame.backgroundImg);
$("#mainPreview").attr("src", frame.mainImg);
$("#carouselFrameModal")
.data("state", "unsaved")
.one("hidden.bs.modal",
function() {
if ($("#carouselFrameModal").data("state") == "saved") {
var data = getCarouselFrameFormData();
selected.text(data.title).data("frame", data);
}
})
.modal("show");
});
$("#carouselModalRemoveFrame").click(function () {
$("#confirm-delete").modal("show");
});
$("#carouselFrameModalForm").find("input:file").change(function() {
var elem = $(this);
var target = elem.data("target");
var preview = elem.data("preview");
FiletoBase64(this, preview, target);
});
$("#carouselModalList").change(function() {
var selected = $("option:selected", this);
$("#carouselModalEditFrame,#carouselModalRemoveFrame").prop("disabled", !selected.length);
});
$("#carouselModalSave").click(function() {
// Validate frameset
var form = $("#carouselModalForm").get(0);
var select = $("#carouselModalList");
if (select.find("option").length == 0) {
select.get(0).setCustomValidity("Need at least one frame");
} else {
select.get(0).setCustomValidity("");
}
if (form.checkValidity()) {
$("#carouselModal").data("state", "saved");
$("#carouselModal").modal("hide");
}
else {
$("#carouselModalForm").addClass("was-validated");
}
});
$("#carouselFrameModalSave").click(function() {
// Validate frame
if ($("#carouselFrameModalForm").get(0).checkValidity()) {
$("#carouselFrameModal").data("state", "saved");
$("#carouselFrameModal").modal("hide");
}
else {
$("#carouselFrameModalForm").addClass("was-validated");
}
});
$('#confirm-delete-delete').click(function () {
$("#carouselModalList option:selected").remove();
$("#confirm-delete").modal("hide");
});
// #region Image FileExplorer Handler
function insertImageToEditor(url) {
var div = $("#editor-container");
var quill = div.data('quill');
var range = quill.getSelection();
quill.insertEmbed(range.index, 'image', url);
}
function CarouselMainimageHandler() {
$("#CarouselMainimageSelectFileExplorer").fileExplorer({
directoryListUrl: '#Url.Action("DirectoryList", "FileTree")',
fileListUrl: '#Url.Action("FileList", "FileTree")'
});
$("#CarouselMainimageSelectModal").modal("show");
}
$("#CarouselMainimageSelectModal").on("hide.bs.modal",
function() {
$("#CarouselMainimageSelectFileExplorer").fileExplorer("destroy");
});
$("#CarouselMainimageSelectSelectButton").click(function() {
var id = $("#CarouselMainimageSelectFileExplorer").fileExplorer("getSelectedFileId");
if (id == null) {
alert("Please select a file");
return;
}
var imageName = $("#CarouselMainimageSelectFileExplorer").fileExplorer("getSelectedFileName");
var imageLink = "#Url.Action("Render", "FileTree")?id=" + id;
$("#mainImageName").val(imageName);
$("#mainImageLink").val(imageLink);
$("#mainImage").attr("src",imageLink);
$("#mainImage").show();
$("#CarouselMainimageSelectModal").modal("hide");
});
function CarouselBackgroundimageHandler() {
$("#CarouselBackgroundimageSelectFileExplorer").fileExplorer({
directoryListUrl: '#Url.Action("DirectoryList", "FileTree")',
fileListUrl: '#Url.Action("FileList", "FileTree")'
});
$("#CarouselBackgroundimageSelectModal").modal("show");
}
$("#CarouselBackgroundimageSelectModal").on("hide.bs.modal",
function() {
$("#CarouselBackgroundimageSelectFileExplorer").fileExplorer("destroy");
});
$("#CarouselBackgroundimageSelectSelectButton").click(function() {
var id = $("#CarouselBackgroundimageSelectFileExplorer").fileExplorer("getSelectedFileId");
if (id == null) {
alert("Please select a file");
return;
}
var imageName = $("#CarouselBackgroundimageSelectFileExplorer").fileExplorer("getSelectedFileName");
var imageLink = "#Url.Action("Render", "FileTree")?id=" + id;
$("#backgroundImageName").val(imageName);
$("#backgroundImageLink").val(imageLink);
$("#backgroundImage").attr("src",imageLink);
$("#backgroundImage").show();
$("#CarouselBackgroundimageSelectModal").modal("hide");
});
function imageHandler() {
$("#imageSelectFileExplorer").fileExplorer({
directoryListUrl: '#Url.Action("DirectoryList", "FileTree")',
fileListUrl: '#Url.Action("FileList", "FileTree")'
});
$("#imageSelectModal").modal("show");
}
$("#imageSelectModal").on("hide.bs.modal",
function() {
$("#imageSelectFileExplorer").fileExplorer("destroy");
});
$("#imageSelectSelectButton").click(function() {
var id = $("#imageSelectFileExplorer").fileExplorer("getSelectedFileId");
if (id == null) {
alert("Please select a file");
return;
}
insertImageToEditor("#Url.Action("Render", "FileTree")?id=" + id);
$("#imageSelectModal").modal("hide");
});
// #endregion
function Save() {
var div = $("#editor-container");
var quill = div.data('quill');
$('#alertSave').show();
$.post({
url: '#Url.Action("Save")',
data: { BodyHtml: quill.root.innerHTML, locationId: #(Model.LocationId?.ToString() ?? "null") },
headers: {
'#Xsrf.HeaderName': '#Xsrf.RequestToken'
}
}).done(function() {
$('#alertSave').hide();
$('#alertSuccess').show();
setTimeout(function() { $('#alertSuccess').hide(); }, 5000);
}).fail(function(jqXhr, error) {
var alert = $('#alertFailure');
var text = $("#alertFailureText");
text.text(error.ErrorMessage);
alert.show();
});
}
function FiletoBase64(input, imgName, Base64TextName) {
var preview = document.getElementById(imgName);
var file = input.files[0];
var reader = new FileReader();
reader.addEventListener("load",
function() {
preview.src = reader.result;
document.getElementById(Base64TextName).value = reader.result;
},
false);
if (file) {
reader.readAsDataURL(file);
}
}
</script>

Dropzone.js when removing a mock file created on page load, the default add files message shows

There is a previous unanswered question about this here but no code or answer was provided. I'm hoping providing some code you'll be able to help me out.
Removing any existing file from Dropzone shows dictDefaultMessage
When I load the page I'm adding mock files to the dropzone. When I click remove on one of those files, the default add image text displays in the dropzone even though there are still files present. How does dropzone keep track of the number of files in the drop zone. I've tried directly modifying the myDropzone.files.length property to match the number of mock files but it breaks the dropzone as I've said in the other question. Here is my code for dropzone.
var jsphotos = '#jsphotos';
var mockFiles = [];
Dropzone.autoDiscover = false;
var fileList = new Array;
var fileListCounter = 0;
var photoDropzone = new Dropzone('#photoDropzone', {
url: 'importphotos.cshtml',
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 5, // MB
method: 'post',
acceptedFiles: 'image/jpeg,image/pjpeg',
dictInvalidFileType: 'Files uploaded must be type .jpg or .jpeg',
init: function () {
this.on("addedfile", function (file) {
// remove size
file.previewElement.querySelector('.dz-size').innerHTML = '';
// add custom button
// Create the remove button
var removeButton = Dropzone.createElement('<i class="fa fa-times-circle-o fa-3x removeButton"></i>');
// Capture the Dropzone instance as closure.
var _this = this;
// Listen to the click event
removeButton.addEventListener("click", function (e) {
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
// Remove the file preview.
_this.removeFile(file);
});
// Add the button to the file preview element.
file.previewElement.appendChild(removeButton);
});
this.on("success", function (file, serverFileName) {
file.previewElement.querySelector('.dz-filename').innerHTML = '<span data-dz-name>'+serverFileName+'</span>';
});
this.on("removedfile", function (file) {
//var rmvFile = "";
//for (f = 0; f < fileList.length; f++) {
// if (fileList[f].fileName == file.name) {
// rmvFile = fileList[f].serverFileName;
// fileListCounter--;
// }
//}
//if (rmvFile) {
// $.ajax({
// url: "deletephoto.cshtml",
// type: "POST",
// data: { "fileList": rmvFile }
// });
//}
});
}
});
$('#photoDropzone').sortable({
items: '.dz-preview',
cursor: 'move',
opacity: 0.5,
containment: "parent",
distance: 10,
tolerance: 'pointer',
sort: function (event, ui) {
var $target = $(event.target);
if (!/html|body/i.test($target.offsetParent()[0].tagName)) {
var top = event.pageY - $target.offsetParent().offset().top - (ui.helper.outerHeight(true) / 2);
ui.helper.css({ 'top': top + 'px' });
}
},
update: function (e, ui) {
// do what you want
}
});
if (jsphotos.length > 0) {
var tmpSplit = jsphotos.split(',');
for (i = 0; i < tmpSplit.length; i++) {
if (tmpSplit[i].length > 0) {
mockFiles.push(tmpSplit[i]);
}
}
}
for (i = 0; i < mockFiles.length; i++) {
// Create the mock file:
var mockFile = { name: mockFiles[i]};
// Call the default addedfile event handler
photoDropzone.emit("addedfile", mockFile);
photoDropzone.emit("success", mockFile, mockFile.name);
// And optionally show the thumbnail of the file:
//photoDropzone.emit("thumbnail", mockFile, '#Globals.tempUploadFolderURL' + mockFile.name);
// Or if the file on your server is not yet in the right
// size, you can let Dropzone download and resize it
// callback and crossOrigin are optional.
photoDropzone.createThumbnailFromUrl(mockFile, '#Globals.tempUploadFolderURL' + mockFile.name);
// Make sure that there is no progress bar, etc...
photoDropzone.emit("complete", mockFile);
// If you use the maxFiles option, make sure you adjust it to the
// correct amount:
//var existingFileCount = 1; // The number of files already uploaded
//Dropzone.options.maxFiles = myDropzone.options.maxFiles - existingFileCount;
}
//photoDropzone.files.length = mockFiles.length;
After attempting to code a solution that monitored the count manually and modified the value of the default text, I didn't want a hack to modify class names to 'fool' the dropzone into thinking there were files. So I added this
photoDropzone.files.push(mockFile);
just below
photoDropzone.emit("complete", mockFile);
and now dropzone knows how many files it has, and everything functions appropriately. Files pushed into the array do not get resubmitted, it's the same as adding the mock preview originally.

Jquery how clean formData object in my own upload plugin

I tried to create my own plugin for upload files via ajax.
If the page where there is the input file is reloaded after upload It seems to work good.
If the page where there is the input file is NOT reloaded after upload (because was reloaded only ajax content) There are problems with IE and Chrome because the files to upload are appended to previous just uploaded (with firefox is ok).
I tried to fix it by cleaning the input file after the first upload but in this way then with IE and Chrome I can no longer upload other files.
MY FIX
complete: function () {
defaults.onFinish.call(this);
// If page where is the input file not reloaded
// after upload files IE and Chrome not working
$this.replaceWith($this.val('').clone(true));
$this.val('');
}
In truth I would clean the formData object after every upload but I haven't been able to do it
MY PLUGIN
;(function ($, window, document, undefined) {
// Function-level strict mode syntax
'use strict';
$.fn.ajaxUpload = function(options) {
var defaults = {
num_files : 0,
max_files : 2,
max_concurrent : 10,
max_filesize : 1024 * 4096,
php_max_size : 1024 * 8192,
allowed_types : ['jpeg','jpg'],
ajax_url : 'action.php',
var_name : 'file',
extra_fields : {},
onFinish : function() {}
};
var options = $.extend(defaults, options);
return this.each(function() {
var $this = $(this);
$this.on('change', function() {
var files = $this[0].files;
var len = files.length;
var items = 0;
var diff_files = parseInt(defaults.max_files - defaults.num_files - len);
if(diff_files < 0) {
return false;
}
if(!maxUploadFiles(len, defaults.max_concurrent)) {
return false;
}
var formdata = new FormData();
jQuery.each(files, function(i, file) {
if(!isOverSized(file, defaults.max_filesize)) {
return false;
}
if(!isAllowedTypes(file, defaults.allowed_types)) {
return false;
}
if(!totalFilesSize(file, defaults.php_max_size)) {
return false;
}
formdata.append(defaults.var_name + '['+i+']', file);
items++;
});
// Append extra data to formdata
$.each(defaults.extra_fields, function(name, value) {
formdata.append(name, value);
});
// Check that files have passed all test
if (len != items) { return false; }
$.ajax({
url: defaults.ajax_url,
data: formdata,
cache: false,
contentType: false,
processData: false,
type: 'POST',
beforeSend: function () {
},
success: function(data) {
totalSize = 0;
},
complete: function () {
defaults.onFinish.call(this);
// If page where is the input file not reloaded
// after upload files IE and Chrome not working
//$this.replaceWith($this.val('').clone(true));
//$this.val('');
}
});
});
});
};
var totalSize = 0;
function totalFilesSize(file, php_max_size) {
totalSize += file.size;
if(totalSize > php_max_size) {
totalSize = 0;
return false;
}
return true;
}
function maxUploadFiles(len, max_concurrent) {
if(len > max_concurrent) {
return false;
}
return true;
}
function isAllowedTypes(file, allowed_types) {
var ext = file.name.split('.').pop().toLowerCase();
if(jQuery.inArray(ext, allowed_types) < 0) {
return false;
}
return true;
}
function isOverSized(file, max_filesize) {
if(file.size > max_filesize) {
return false;
}
return true;
}
})(jQuery, window, document);
According to you that changes should I do to solve my problem?
Thank you
EDIT
I add this line on complete, and It seems to work
$this.val('');
$this.wrap('<form>').parent('form').trigger('reset');
$this.unwrap();
$this.replaceWith($this.clone());
The problem with your plugin is that you keep a reference to the original input with $this and then tried to replace it with a clone. Because you are cloning is better to get a new reference each time so you should unbind and bind .
(function ($, window, document, undefined) {
// Function-level strict mode syntax
'use strict';
$.fn.ajaxUpload = function (options) {
var defaults = {
num_files: 0,
max_files: 2,
max_concurrent: 10,
max_filesize: 1024 * 4096,
php_max_size: 1024 * 8192,
allowed_types: ['jpeg', 'jpg'],
ajax_url: 'action.php',
var_name: 'file',
extra_fields: {},
onFinish: function () {}
};
var options = $.extend(defaults, options);
var bindInput = function (elem) {
var element = $(elem),
bindFunc = function (evt) {
var files = evt.currentTarget.files;
var len = files.length;
var items = 0;
var diff_files = parseInt(defaults.max_files - defaults.num_files - len);
if (diff_files < 0) {
return false;
}
if (!maxUploadFiles(len, defaults.max_concurrent)) {
return false;
}
var formdata = new FormData();
jQuery.each(files, function (i, file) {
if (!isOverSized(file, defaults.max_filesize)) {
return false;
}
if (!isAllowedTypes(file, defaults.allowed_types)) {
return false;
}
if (!totalFilesSize(file, defaults.php_max_size)) {
return false;
}
formdata.append(defaults.var_name + '[' + i + ']', file);
items++;
});
// Append extra data to formdata
$.each(defaults.extra_fields, function (name, value) {
formdata.append(name, value);
});
// Check that files have passed all test
if (len != items) {
return false;
}
$.ajax({
url: defaults.ajax_url,
data: formdata,
cache: false,
contentType: false,
processData: false,
type: 'POST',
beforeSend: function () {},
success: function (data) {
totalSize = 0;
},
complete: function () {
defaults.onFinish.call(this);
var previous = $(evt.currentTarget);
previous.off('change', bindFunc);
var newElem = previous.val('').clone(true)
previous.replaceWith(newElem);
bindInput(newElem);
}
});
};
element.on('change', bindFunc);
};
return this.each(function () {
bindInput(this)
});
};
var totalSize = 0;
function totalFilesSize(file, php_max_size) {
totalSize += file.size;
if (totalSize > php_max_size) {
totalSize = 0;
return false;
}
return true;
}
function maxUploadFiles(len, max_concurrent) {
if (len > max_concurrent) {
return false;
}
return true;
}
function isAllowedTypes(file, allowed_types) {
var ext = file.name.split('.').pop().toLowerCase();
if (jQuery.inArray(ext, allowed_types) < 0) {
return false;
}
return true;
}
function isOverSized(file, max_filesize) {
if (file.size > max_filesize) {
return false;
}
return true;
}
})(jQuery, window, document);
{Edit}
The problem that originate your question is the nightmare of every file upload plugin developer. As you are developing a plugin you should be aware that the input tag may contain other styles and event handlers set by the consumer of the plugin that you must preserve or you will break existing functionality.
For security reasons the value of the input type file cannot be changed with javascript. There are a lot of answers in SO about that. Search for clear+input+file and see for yourself, the most remarkable is this Clearing <input type='file' /> using jQuery
As you can see there are basically two choices:
Clone the input and call val('') before cloning (calling jQuery $(input).val('') is not the same that calling input.value = '').
The problems of this approach is for example that in IE this event is called twice when clearing the file input and you must be carefull about releasing memory and references to the input being replaced while preserving current styles and event handlers that were not set by your plugin
The second is better but has issues as well. Wrap your input in a form tag and call the form's reset method.
input.wrap('<form>').parent('form').trigger('reset');
input.unwrap();
Check the docs about the sintax of the form tag and you will see the following quote
Note: It's strictly forbidden to nest a form inside another form. Doing so can behave in an unpredictable way that will depend on which browser the user is using.
The main reasoning behind that is that your plugin can be applied to an input tag that is already inside a form leaving you with invalid html so you must wrap the form call the reset method and remove this form right away. Also remember that forms may have visual styles applied to them breaking the user interface if you leave them around.
In the second alternative is easier to fix your code. Just change the complete callback like this. No cloning is needed in this case.
complete: function () {
defaults.onFinish.call(this);
$this.wrap('<form>').parent('form').trigger('reset');
$this.unwrap();
}
This changes should happen so fast that the users will not notice them. I tested with 1000 elements around and no visual glitches were visible.

processQueue() is not working in multiple uploads

I use dropzone.js for uploading image. I use this code
init: function() {
var submitButton = document.querySelector("#submit-all")
myDropzone = this; // closure
submitButton.addEventListener("click", function() {
var e = document.getElementById("test");
var strUser = e.options[e.selectedIndex].value;
if (strUser == 0) {
alert("First name must be filled out");
return false;
}
else
{
myDropzone.processQueue(); // Tell Dropzone to process all queued files.
}
});
}
But My processQueue upload only two image.But if i using auto process then all file uploaded.
I am trying to use this in my processquee function
while (i < parallelUploads) {
if (!queuedFiles.length) {
return;
}
this.processFile(queuedFiles.shift());
i++;
}
Try to set options of your dropzone.js:
parallelUploads: 30,
uploadMultiple: true
in parallelUploads you can set a different value from 1 and higher.
Good day to you.

Dropzone show files exist

I have a problem I am using on my website dropzone.js, but It doesnt work good for me. I have 2 problems. JSON works fine.
In existing files I havent remove button
When I upload by drag and drop it upload file twice
var FormDropzone = function () {
$(function() {
var projectID = $("#projectID").html();
var myDropzone = new Dropzone("#my-dropzone");
$.getJSON('http://'+window.location.hostname+'/project/getFile/'+projectID, function( json ) {
for (var i = 0; i < json.length; i++) {
var mockFile = { name: json[i].name, size: json[i].size };
myDropzone.emit("addedfile", mockFile);
myDropzone.emit("thumbnail", mockFile, "../../upload_files/project/1/"+json[i].name);
};
})
});
return {
//main function to initiate the module
init: function () {
Dropzone.options.myDropzone = {
init: function() {
this.on("success", function(file, serverFileName) {
FileList = {"serverFileName" : serverFileName, "fileName" : file.name };
});
this.on("addedfile", function(file) {
// Create the remove button
var removeButton = Dropzone.createElement("<button class='btn btn-sm btn-block'>Remove file</button>");
// Capture the Dropzone instance as closure.
var _this = this;
// Listen to the click event
removeButton.addEventListener("click", function(e) {
var projectID = $("#projectID").html();
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
$.post( "http://"+window.location.hostname+"/project/deleteFile", { file_name: file.name, project_id: projectID, FileList : FileList["serverFileName"]});
// Remove the file preview.
_this.removeFile(file);
});
// Add the button to the file preview element.
file.previewElement.appendChild(removeButton);
});
}
}
}
};
}();
For adding remove button you have to add delete option i.e addRemoveLinks : true to the dropzone object.
just like this one :
Dropzone.options.mysample = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 1, // MB
addRemoveLinks : true,
};

Categories

Resources