Dynamically append Dropzone image upload fields - javascript

In my application I have added image upload fields dynamically using jquery append
So I use dropzone js and it not work when it append because it not initialize in document load.
So how could I load that dynamically
$(add_button).click(function(e){
$(wrapper).append(
'<div class="dropzone small-dropzone feedDropZone">' +
'<div class="dz-message" data-dz-message><p>Drop image or click to select</p></div></div>');
}
});
Dropzone code is
$('#add').on('click', '.feedDropZone', function(){
// do something here
Dropzone.autoDiscover = false;
var minImageWidth = 800, minImageHeight = 600;
$(this).dropzone({
url: base_url + "admin/feed/upload",
maxFiles: 1,
maxFilesize: 5,
acceptedFiles: ".jpeg,.jpg",
addRemoveLinks: true,
maxfilesexceeded: function (file) {
},
createImageThumbnails: true,
success: function (file, response) {
imgObject = JSON.parse(response);
},
error: function (file, response) {
},
init: function () {
this.on("thumbnail", function (file) {
if (file.width < minImageWidth || file.height < minImageHeight) {
file.rejectDimensions();
}else if(file.size/(1024*1024) > 5){
file.rejectFilesize();
}
else {
file.acceptDimensions();
}
});
}
});
});
I'm getting below error:
Error: No URL provided.
throw new Error("No URL provided.");

Related

Multiple File Upload using dropzone and with other forms fields with FormValidation plugin

This is the image of form which I have designed in my project Now my requirement is to upload multiple files and with other form values over a single backend call.
<script>
<form class="form-horizontal" name="addColorForm" id="addColorForm"
enctype="multipart/form-data"
method="POST">
//Colour Name and Code fileds
//Files Uploader Plugin (Dropzone)
<input type="file" name="artworkFiles[]" style="visibility: hidden"/>
</form>
Now my script part
<script>
var validCode = function () { // my custom validation };
FormValidation.validators.validCode = validCode;
FormValidation.formValidation(
document.getElementById('addColorForm'),
{
fields: {
colorName: {
validators: {
notEmpty: {
message: '${message(code:"blank.error.message", default:"This field must be entered")}'
},
}
},
},
plugins: { //Learn more: https://formvalidation.io/guide/plugins
trigger: new FormValidation.plugins.Trigger(),
// Bootstrap Framework Integration
bootstrap: new FormValidation.plugins.Bootstrap(),
// Validate fields when clicking the Submit button
submitButton: new FormValidation.plugins.SubmitButton(),
// Submit the form when all fields are valid
// defaultSubmit: new FormValidation.plugins.DefaultSubmit(),
}
}
).on('core.form.valid', function () {
saveColor();
});
function saveColor() {
var url = "url";
var form = $("#createArtworkForm");
var formData = new FormData(form[0]);
$.ajax({
url: url,
type: 'POST',
enctype: 'multipart/form-data',
data: formData,
success: function (data) {},
cache: false,
contentType: false,
processData: false,
error: function () { }
});
}
var artworkColorsFiles = $('#kt_dropzone').dropzone({
url: "https://www.google.com", // Set the url for your upload script location
paramName: "media", // The name that will be used to transfer the file
maxFiles: 1,
maxFilesize: 40, // MB
addRemoveLinks: true,
acceptedFiles: "image/*",
autoProcessQueue: false,
accept: function (file) {
//Logic to add multiple files in an input type hidden which is declared above
let fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onloadend = function () {
let content = fileReader.result;
$('#artworkFiles').val(content);
file.previewElement.classList.add("dz-success");
}
file.previewElement.classList.add("dz-complete");
}
});
</script>
My questions is how to implement this or how should i add my all files(max 3) in a input type file field declared as visibility hidden.
The same I did in my project here is the code hope it will help you.
you have to use the dropzone function to send file and form data in sendingmultiple function you have to add a loop through your formdata enter code here
var data = $("form#OpportunityForm").serializeArray();
$.each(data, function (key, el) {
.append(el.name, el.value);
});
$(document).ready(function () {
zdrop = new Dropzone('#dropzone', {
url: '#Url.Action("SaveOpportunity", "Masters")',
maxFiles: 500,
maxFilesize: 300,
parallelUploads: 100,
addRemoveLinks: true,
autoProcessQueue: false,
uploadMultiple: true,
removeFilePromise: function () {
return new Promise((resolve, reject) => {
let rand = Math.floor(Math.random() * 3)
console.log(rand);
if (rand == 0) reject('didnt remove properly');
if (rand > 0) resolve();
});
},
sendingmultiple: function (file, xhr, formData) {
var data = $("form#OpportunityForm").serializeArray();
$.each(data, function (key, el) {
.append(el.name, el.value);
});
debugger
$("form#OpportunityForm").find("input[type=file]").each(function (index, field) {
const file = field.files[0];
formData.append('itemfile', file);
});
},
successmultiple: function (file, responseText) {
jQuery('form#OpportunityForm').find('textarea, input').each(function () {
jQuery(this).val('');
});
clear();
swal.fire("Opportunity Details Saved!", "Opportunity details Saved Successfully!", "success");
OpportunityMstList();
GetOpportunityMstList();
location.reload();
$("#myModal").modal('hide');
},
});
after adding this on the form submit button click you have to add this for creating blob file when you post data without image file.
jQuery(document).on('click', 'button#saveOpportunity', function (e) {
e.preventDefault();
if ($("#OpportunityForm").validate().form()) {
if (zdrop.files.length == 0) {
var blob = new Blob();
blob.upload = { 'chunked': zdrop.defaultOptions.chunking };
zdrop.uploadFile(blob); // just submit the form
} else if (zdrop.getRejectedFiles().length > 0) {
alert("The attached file is invalid");
} else {
zdrop.processQueue();
}
}
});

dropzone.js options maybe not placed in corret place

I´m using Dropzone.js but my option are not recognized at all. I tried to place the code different places, but I´m not sure where it should be placed. I read that the Dropzone.options must be out of document.ready or it wont work.
<form action="/" method="post" class="dropzone" id="my-dropzone"></form>
<script>
var myDropzone = new Dropzone("#my-dropzone");
// Disabling autoDiscover, otherwise Dropzone will try to attach twice.
Dropzone.autoDiscover = false;
Dropzone.options.myDropzone = {
paramName: 'photo',
acceptedFiles: '.jpg, .jpeg, .png',
maxFilesize: 1,
init: function() {
this.on("uploadprogress", function(file, progress) {
console.log("File progress", progress);
});
}
}
Maybe you can try this, I hope it helps.
Click here for the JSFiddle Demo.
Other alternative code, click here.
$(function() {
Dropzone.options.myDropzone = {
maxFilesize: 1,
addRemoveLinks: true,
dictResponseError: 'Server not Configured',
acceptedFiles: ".png,.jpg,.jpeg",
init: function() {
var self = this;
// config
self.options.addRemoveLinks = true;
self.options.dictRemoveFile = "Delete";
//New file added
self.on("addedfile", function(file) {
console.log('new file added ', file);
});
// Send file starts
self.on("sending", function(file) {
console.log('upload started', file);
$('.meter').show();
});
// File upload Progress
self.on("totaluploadprogress", function(progress) {
console.log("progress ", progress);
$('.roller').width(progress + '%');
});
self.on("queuecomplete", function(progress) {
$('.meter').delay(999).slideUp(999);
});
// On removing file
self.on("removedfile", function(file) {
console.log(file);
});
}
};
})

Dropzone.js getting image for Preview

I'm trying to get the real image that is queued in the Dropzone and show a preview, but the only image i can get is the one of the thumbnail, is there a way to get the real image?
here is my code:
var uploadDrop = new Dropzone("#my-awesome-dropzone", {
acceptedFiles: "image/png",
url: "${g.createLink(controller:'perfil',action: 'saveFile')}",
maxFiles: 1, // Number of files at a time
maxFilesize: 1, //in MB
autoProcessQueue: false,
maxfilesexceeded: function(file){
alert('You have uploaded more than 1 Image. Only the first file will be uploaded!');
},
init: function(){
this.on("addedfile", function() {
if (this.files[1]!=null){
this.removeFile(this.files[0]);
}
});
},
thumbnail: function(file, dataUrl) {
// Display the image in your file.previewElement
$(file.previewElement).removeClass("dz-file-preview").addClass("dz-image-preview");
$(file.previewElement).find(".dz-image img").attr("src",dataUrl);
$("#preview").attr("src",dataUrl);
},
success: function (response) {
var x = JSON.parse(response.xhr.responseText);
var message=x.data.message;
if (message.pass) {
originalLogoName=x.data.data.logoName
pasoPorSubida=true;
simpleMessage(message.title, message.body, "success");
this.removeAllFiles(); // This removes all files after upload to reset dropzone for next upload
} else {
simpleMessage(message.title, message.body, "error");
}
},
addRemoveLinks: true,
removedfile: function(file) {
var _ref; // Remove file on clicking the 'Remove file' button
if(!success){
$("#preview").attr("src",originalLogoUrl+"/"+originalLogoName);
}else{
success=false;
}
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
});

Dropzone not validating maximum number of files

I am using dropzone for uploading files , I have set the file limitations upto maximum six files, this code is working if I upload one image at a time, but if I select more then six images by pressing control button at the start of uploading files then it does not validate the files and uploads all files. I am using laravel for backend, My code is:-
Dropzone.options.myAwesomeDropzone = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 1, // MB
maxFiles: 6,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
clickable: true,
init: function () {
this.on("success", function(file, responseText) {
file.previewTemplate.setAttribute('id',responseText[0].id);
});
this.on("thumbnail", function(file) {
if (file.width < 350 || file.height < 200) {
file.rejectDimensions()
}
else {
file.acceptDimensions();
}
});
},
accept: function(file, done) {
file.acceptDimensions = done;
file.rejectDimensions = function() { done("Image width or height should be greater than 350*200"); };
},
removedfile: function(file){
var name = file.name;
$.ajax({
type: 'POST',
url: ajax_url+'listing/deleteListingImage/'+name,
dataType: 'html'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
},
dictDefaultMessage: "Drop your files to upload"
}
Thanks
You can remove the extra files using the method removeFile(file) when maxfilesexceeded is called.
Like this:
Dropzone.options.myAwesomeDropzone = {
maxFiles: 2,
autoProcessQueue: false,
init: function(){
var myDropZone = this;
myDropZone.on('maxfilesexceeded', function(file) {
myDropZone.removeFile(file);
});
}
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.3.0/dropzone.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.3.0/min/dropzone.min.js"></script>
<form action="/file-upload"
class="dropzone"
id="my-awesome-dropzone">
</form>
http://output.jsbin.com/dodajij

How to pass DropZone JSON object to AngularJS?

In my Angular app, I'm using Dropzone with JQuery to upload files. I'm successfully able to upload file to my server and receive the response data. Now I need to pass that response data from JQuery to my AngularJS controller.
This is my dropzone code:
<script type="text/javascript">
Dropzone.autoDiscover = false;
$(document).ready(function() {
// Smart Wizard
$('#wizard').smartWizard({labelFinish:'Upload'});
$('#file-dropzone').dropzone({
url: "UploadData/",
maxFilesize: 1024000,
paramName: "uploadfile",
acceptedFiles: ".csv",
maxFiles: 1,
dictDefaultMessage: "Drop CSV file here",
maxThumbnailFilesize: 5,
dictMaxFilesExceeded: "You can only uplaod one file",
init: function() {
this.on("sending", function(file, xhr, formData){
$(".busy-modal").show();
formData.append("format", $("#format").val());
});
this.on('success', function(file, json) {
$(".busy-modal").hide();
alert(JSON.stringify(json));
});
this.on('addedfile', function(file) {
});
}
});
});
function ResetDropZone()
{
Dropzone.forElement("#file-dropzone").removeAllFiles(true);
}
</script>
This is where I receive response data in JSON.
this.on('success', function(file, json) {
$(".busy-modal").hide();
alert(JSON.stringify(json));
});
I need to pass this json object to AngularJS controller. How can I do it?
So I got to do it by myself. Here's how:
I added a hidden text input with ng-model and ng-change attributes.
<input type="text" hidden id="fileResult" ng-model="fileResult" ng-change="fileResult_Changed()"/>
In my dropzone success function I changed value of that field and triggered input so that my ng-change event would fire.
this.on('success', function(file, json) {
$(".busy-modal").hide();
//alert(JSON.stringify(json));
$("#fileResult").val(JSON.stringify(json));
$("#fileResult").trigger('input');
});
And this is my ng-change event in my controller where I received data successfully
$scope.fileResult_Changed = function()
{
alert($scope.fileResult);
}
Ta-da!
Create dropzone directive
angular.module('myApp').directive('dropzone', ['$cookie', function ($cookie) {
return {
restrict: 'C',
scope: {
fileList: '=?'
},
link: function(scope, element, attrs) {
var config = {
url: '/upload',
maxFilesize: 16,
paramName: "file_content",
maxThumbnailFilesize: 10,
parallelUploads: 1,
autoProcessQueue: false,
headers: {
'X-CSRFToken': $cookies.get('csrftoken')
}
};
var eventHandlers = {
'addedfile': function(file) {
var dz = this;
scope.$apply(function () {
scope.file = file;
if (dz.files[1]!=null) {
dz.removeFile(dz.files[0]);
}
scope.fileAdded = true;
scope.processDropzone();
});
},
'success': function (file, response) {
// Do some thing on success
scope.$apply(function () {
scope.resetFile(file);
};
},
'error': function (file, reason) {
// Do something on error
}
};
scope.dropzone = new Dropzone(element[0], config);
angular.forEach(eventHandlers, function(handler, event) {
scope.dropzone.on(event, handler);
});
scope.processDropzone = function() {
scope.dropzone.processQueue();
};
scope.resetDropzone = function() {
scope.dropzone.removeAllFiles();
};
scope.resetFile = function(file) {
scope.dropzone.removeFile(file);
};
}
}
}]);

Categories