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);
};
}
}
}]);
Related
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();
}
}
});
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);
});
}
};
})
I am trying to implement Bootstrap Dropzone on a website but I am facing a problem getting the success message. Below is my code.
var mydropzone = new Dropzone("#dropzonejs-example", {
url: "/Home/FilesUpload/",
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 10,
addRemoveLinks: true,
init: function() {
this.on("sending", function(file, xhr, formData) {
formData.append("is_visible", $('#is_visible').is(':checked'));
this.removeFile(file);
this.on("success", function(fname) {
console.log("ok");
});
});
},
});
$("#uploadbtn").click(function() {
mydropzone.processQueue();
});
My controller returns a string so I want to catch the string here. How can it be possible or where am I doing the mistake? Please correct my code.
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.");
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
)