Dropzone: Binding to init - javascript

I'm following this tutorial on mocking existing files to a Dropzone enabled form, but am having trouble hooking onto the init function. Here's what I have so far:
var imageUpload;
if ($('.js-listing__images-upload').length) {
imageUpload = new Dropzone('.js-listing__images-upload', {
addRemoveLinks: true,
maxFiles: 5,
maxFilesize: 3,
acceptedFiles: 'image/jpeg,image/png,image/gif'
});
imageUpload.on('init', function() {
var listingID, thisDropzone;
console.log('dropzone init');
thisDropzone = this;
listingID = $('#manage-images').data('listing');
$.ajax({
url: dashboard.images.list,
data: {
listing: listingID
},
success: function(data) {
console.log('ajax for list done');
$.each(data, function(key, value) {
var mockFile;
mockFile = {
name: value.name,
size: value.size
};
thisDropzone.options.addedfile.call(thisDropzone, mockFile);
thisDropzone.options.thumbnail.call(thisDropzone, mockFile, '/uploads/thumb/listings/' + value.name);
});
}
});
});
}
None of my console.log() fire, but I'm unsure as to what the issue could be. Following Dropzone's config, I should be able to hook onto events using simple on mechanisms. Thanks all!
Update
The following does work:
# When images are removed
# Dropzone
imageUpload.on 'removedfile', (file) ->
if file.xhr
imageID = JSON.parse file.xhr.response
$.ajax
url: dashboard.images.destroy
data: { image: imageID }
success: () ->
return
So it's something about the init function that I'm having trouble with.

The init function can be binded directly to your new Dropzone instantiation:
if $('.js-listing__images-upload').length
imageUpload = new Dropzone(
'.js-listing__images-upload',
addRemoveLinks: true
maxFiles: 5
maxFilesize: 3
acceptedFiles: 'image/jpeg,image/png,image/gif'
init: ->
thisDropzone = this
$.ajax
url: dashboard.images.list
data: { listing: $('#manage-images').data('listing') }
success: (data) ->
$.each data, (key, value) ->
mockFile =
name: value.name
size: value.size
thisDropzone.options.addedfile.call thisDropzone, mockFile
thisDropzone.options.thumbnail.call thisDropzone, mockFile, '/uploads/thumb/listings/' + value.name
return
return
return
)

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 5.0 - use existing images and send the data to the server

I have successfully used Dropzone to display existing files from my server. However, when I submit the form, only new files are submitted to the server, so I don't know if the user has deleted any. Essentiall I want to send the data for all the files currently displayed, including the 'mocked' files and the newly uploaded ones.
I am using autoProcessQueue: false so that I can have a separate submit button to send the data to the server.
My Code:
Dropzone.options.createListingForm = {
autoProcessQueue: false,
uploadMultiple: true,
previewsContainer: '.create-listing-form-uploads',
parallelUploads: 100,
maxFiles: 100,
addRemoveLinks: true,
init: function () {
var thisDropzone = this;
var photos = form.data('photos');
$.each(photos, function (key, photo) {
var mockFile = {
name: photo.name,
size: photo.size,
type: photo.type,
accepted: true
};
thisDropzone.files.push(mockFile); // add to files array
thisDropzone.emit("addedfile", mockFile);
thisDropzone.emit("thumbnail", mockFile, photo.path);
thisDropzone.emit("complete", mockFile);
});
}
};
form.on('click', '.create-listing-form-save-photos', function () {
$('.dropzone').get(0).dropzone.processQueue();
return false;
});
Thanks to this answer for the first part of my code:
https://stackoverflow.com/a/45701181/5482719
Each time a file (including mock Files) is removed/deleted from the dropzone, the removedfile event is fired.
You could use this event to delete the removed file from your server as follows:
myDropzone.on("removedfile", function(file) {
// 'file' parameter contains the file object.
console.log('Removed File', file);
// Delete file from server
$.ajax({
type: 'POST',
url: 'url/that/handles/delete',
data: {
fileName: file.name,
},
dataType: 'json'
}).done(function (response) {
// check repsonse, notify user
}).fail(function(resp) {
console.log('xhr failed', resp);
}).always(function(resp) {
// do nothing for now
});
});
Hope that helps.

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

DropZone Replace image in init

I used this code to upload image from database in init. Now I want when upload a new image to remove this initial image.
var o = $("div#uploader").dropzone({
url: "../../Merchant/UploadLogo",
paramName: "logo",
maxFiles: 1,
//enqueueForUpload: false,
maxfilesexceeded: function (file) {
this.removeAllFiles();
this.addFile(file);
},
addRemoveLinks: true,
uploadMultiple: false,
dictRemoveFile: "حذف",
removedfile: function(file) {
RemoveFile("Logo");
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
},
init: function() {
var mockFile = { name: "avatar1.jpg", size: 12345, type: 'image/jpeg', url: "../../Merchant/GetLogo" };
this.options.addedfile.call(this, mockFile);
this.options.thumbnail.call(this, mockFile, mockFile.url);//uploadsfolder is the folder where you have all those uploaded files
}
});
I'm assuming you want to replace the old image in the Dropzone whenever a new Image is successfully uploaded. You can do that by combining the this.on('success') and this.removeFile methods provided by Dropzone:
Dropzone.options.myDropzone = {
init: function() {
this.on('success', function(file, message) {
if (this.files.length > 1) {
this.removeFile(this.files[0]);
}
});
// ...
}
};
For this to work, your mockFile must also be registered as one of the files of your Dropzone. To do that, you can push it into the this.files array in your init, right after displaying it:
// Create and Display Mock File
var mockFile = { name: "avatar1.jpg", size: 12345, url: '/image.png' };
this.options.addedfile.call(this, mockFile);
this.options.thumbnail.call(this, mockFile, mockFile.url);
// Register it
this.files = [mockFile];
Source:
Dropzone#SuccessEvent,
Dropzone#Methods and Experience

Dropbox uploader Cannot call method 'submit' of undefined

I have some problems with Dropbox uploader in my Wordpress site.
It gives me 'Uncaught TypeError: Cannot call method 'submit' of undefined' on this lines:
$('#fileupload')
.bind('fileuploadstop', function (e, data) {
//window.location.href = 'http://hiphopsmurf.com';
$('#multimages', top.document).val(upfiles);
parent.document.forms["multi_image"].submit();
//parent.tb_remove();
});
Here is whole document code:
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload();
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
if (window.location.hostname === 'blueimp.github.com') {
// Demo settings:
$('#fileupload').fileupload('option', {
url: '//jquery-file-upload.appspot.com/',
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
process: [
{
action: 'load',
fileTypes: /^image\/(gif|jpeg|png)$/,
maxFileSize: 20000000 // 20MB
},
{
action: 'resize',
maxWidth: 1440,
maxHeight: 900
},
{
action: 'save'
}
]
});
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//jquery-file-upload.appspot.com/',
type: 'HEAD'
}).fail(function () {
$('<span class="alert alert-error"/>')
.text('Upload server currently unavailable - ' +
new Date())
.appendTo('#fileupload');
});
}
} else {
$('#fileupload').fileupload('option', {
//maxFileSize: 5000000,
maxFileSize: 1048576,
//acceptFileTypes: /(\.|\/)(gif|jpe?g|png|psd)$/i,
acceptFileTypes: /(\.|\/)(doc|docx|gif|jpg|jpeg|pdf|png|psd|tif|tiff)$/i,
singleFileUploads: true,
sequentialUploads: true,
autoUpload: true,
});
var upfiles = "";
$('#fileupload')
//.bind('fileuploaddrop', function (e, data) {$.each(data.files, function (index, file) {alert('Added file: ' + file.name);});})
//.bind('fileuploaddrop', function (e, data) {$.each(data.files, function (index, file) { upfiles += file.name + ",";});})
.bind('fileuploaddone', function (e, data) {$.each(data.files, function (index, file) { upfiles += file.name + ",";});})
.bind('fileuploadchange', function (e, data) {/* ... */})
//fail: function (e, data) {data.submit();}
//.fileupload({fail: function (e, data) {alert('FAIL');}});
;
$('#fileupload')
.bind('fileuploadstop', function (e, data) {
//window.location.href = 'http://hiphopsmurf.com';
$('#multimages', top.document).val(upfiles);
parent.document.forms["multi_image"].submit();
//parent.tb_remove();
});
}
});
I'm kind a week in Java script, so will appreciate for any help.
Generally, when working with JavaScript / jQuery when you receive a "method is undefined" error there's an issue with your selector.
I would use a jQuery selector to submit the form. Try replacing the problem line with this:
$('#multi_image').submit();
(That assumes your form has an id attribute of "multi_image").

Categories