After image uploaded through dropzone, access parent div - javascript

I am confuse i dont know how to access parent div. Let me summarize it!
Actually i have multiple dropzone which i initialize using class '.abc'
above each dropzone there is input where i put image name for uploading. here is my code
$('.kt_dropzone_1').dropzone({
url: base_url + 'product/uploadPic', // Set the url for your upload script location
paramName: "file", // The name that will be used to transfer the
maxFiles: 1,
maxFilesize: 5, // MB
addRemoveLinks: true,
accept: function (file, done) {
done();
},
success: function (file, response) {
alert($(this).attr('data-abc')); // undefined
alert($(this).parent().parent.html()); // undefined
},
});
here is html this is in looop so consider it multiple
<input type="hidden" class="img-upload" name="old" value=""/>
<div class="col-md-12 pull-left">
<div class="dropzone dropzone-default kt_dropzone_1">
<div class="dropzone-msg dz-message needsclick">
<h3 class="dropzone-msg-title">Drop files here or click to upload.</h3>
<span class="dropzone-msg-desc">This is just a demo
dropzone. Selected files are <strong>not</strong>
actually uploaded.</span>
</div>
</div>
</div>
i try use custom attribute to pass input id dynamic still not work
i dont know how to get current div object to access parent html or input or div

I could suggest you small changes for this. Move input type hidden inside of
and just above the dropzone div.
Now to refer the correct dropzone please give a try to following updated code.
$('.kt_dropzone_1').dropzone({
var this_dropzone = $(this);
url: base_url + 'product/uploadPic', // Set the url for your upload script location
paramName: "file", // The name that will be used to transfer the
maxFiles: 1,
maxFilesize: 5, // MB
addRemoveLinks: true,
accept: function (file, done) {
done();
},
success: function (file, response) {
this_dropzone.closest("div").find(".img-upload").attr('data-abe', 'value to be set');
this_dropzone.closest("div").find(".img-upload").val('you can set anyvalue here');
},
});
This should work as you want!

Related

Javascript parameter to function that loads with page, Uppy File Upload

Uppy is used for uploading files by drag & drop interface.
I want to pass a value input given by user from html interface
but the javascript is already processed before the user gives his input.
if i use .onchange() with the userinput then it does not destroy/clear the previously created file drop area but creates too many new file drop areas inside #drag-drop-area
<input id="userinput" value="Car">
<div id="#drag-drop-area"></div>
var userinput = document.getElementById("userinput").value
var URL = 'example.com/post-submit/?category='+userinput;
var uppy = Uppy.Core()
.use(Uppy.Dashboard, {
inline: true,
target: '#drag-drop-area',
inputName: 'imageFile[]',
height:"250px",
width:"100%"
})
.use(Uppy.XHRUpload, {endpoint: URL", headers: {
'X-CSRF-Token': " {{csrf_token()}} "}
})
uppy.on('complete', (result) => {
console.log('Upload complete! ', result.successful)
})

How to display uploaded document inside a dropzone form in an edit modal?

I am using the same dropzone form to upload different documents. After upload I need to open a modal for each one document to give the possibility to modify, so i show document uploaded inside the dropzone when i open the modal with this code
$("#mydropzone").dropzone({
acceptedFiles: ".pdf,.tiff,.png,.jpeg,.jpg,.bmp",
dictDefaultMessage: "Drop files or click here to upload a new DICOM series ...",
uploadMultiple: true,
parallelUploads: 10,
paramName: "file",
autoProcessQueue: false,
clickable:'#dropzoneModal',
previewTemplate: document.querySelector('#preview_template').innerHTML,
init : function() {
modalDropzone = this;
fatturaId = thisId-1;
for(var i=0;i<dropzones[fatturaId].files.length;i++){
var mockFile = {
name: dropzones[fatturaId].files[i].name,
size: dropzones[fatturaId].files[i].size,
status: Dropzone.ADDED,
accepted: true
};
modalDropzone.emit("addedfile", mockFile);
modalDropzone.files.push(mockFile);
modalDropzone.createThumbnailFromUrl(mockFile, opts.imageURL, function() {
modalDropzone.emit("complete", mockFile);
})
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The documents uploaded are saved in dropzones[fatturaId].files, that why i iterate it
The first time the file shows correctly when i open the edit modal, while the second time the dropzone shows empty without any document in it, showing an error in console:
Uncaught Error: Dropzone already attached.

Dropzone check if files names exists before processing queue

I am using dropzone for uploading files which I save with some meta data in a database in the backend.
When a user tries to upload a bulk of files I want to check if he has already uploaded a file with this name and warn him with an alert with an option to continue ot stop.
So I disabled the autoProcessQueue.
I am also listening for addedfile event, I get the name, I perform an ajax to check if it exists in the database and return true or false, good.
Let's say the user tries to upload 40 files which all already exist, I don't want 40 warnings that this file already exists, I want one notification printing all 40 filenames.
I was looking for addedfile but for multiple files, I didn't found a solution.
Here is my code for now
This is where I'm stuck
How can I know when I've checked every file ?
$(document).ready(function() {
#if(isset($checkRoute))
function filenameExists(name) {
$.ajax({
type: 'GET',
url: '{{ $checkRoute }}',
data: {
name: name
}
})
.done(function(res) {
// returns true or false
return res
})
.fail(function(err) {
console.log(err)
})
}
#endif
let existingFilenames = []
let fileCount = 0
$('#{{ $element_id }}').dropzone({
url: "{{ $upload }}", // Set the url for your upload script location
paramName: "documents", // The name that will be used to transfer the file
maxFiles: 100,
maxFilesize: 100, // MB
parallelUploads: 100,
timeout: 240000,
addRemoveLinks: true,
acceptedFiles: "application/msword, application/vnd.ms-excel, application/pdf, image/*, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, image/*",
uploadMultiple: true,
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
},
init: function() {
#if(isset($checkRoute))
this.on('addedfile', function(file) {
console.log(this.getAcceptedFiles())
fileCount++
if (filenameExists(file.name)) {
console.log(file.name)
existingFilenames.push(file.name)
}
})
#endif
},
autoProcessQueue: false,
sendingmultiple: function (files) {
// Begin loading
KTApp.blockPage({
overlayColor: '#000000',
type: 'v2',
state: 'success',
message: '{{ __('documents_uploading') }}'
});
},
queuecomplete: function () {
// End loading
KTApp.unblockPage();
$.notify({
// options
message: '{{ __('documents_upload_success') }}'
}, {
// settings
type: 'success',
placement: {
from: "top",
align: "center"
},
animate: {
enter: 'animated fadeInDown',
exit: 'animated fadeOutUp'
},
});
window.location.replace("{{ $redirect }}");
}
});
});
Another thing that concerns me is how will I process the queue at the press of the button in the notification.
I had a similar problem as i wanted to provide the user with a dropdown of different upload directories on the server.
As each directory has a different ruleset of acceptedFiles, the static option acceptedFiles was out of the question.
Instead i used a combination of listening to the drop event on dropzone init and to "extend" the accept function:
The drop event gets the total number of files dropped and stores it in droppedFilesCounter. It also initializes/resets a global Object dzCustomFeedback and clears the "feedback" area from prior feedback.
The extended accept function, which is called for by each dropped file checks which upload directory is currently selected and compares the current file extension against the configured accepted ones.
If there is a match the done() function "bubbles" an "all clear".
Otherwise the file is removed from the preview list (or actually never makes it into it) and the global dzCustomFeedback Object cumulates error-messages of the type invalidFileTypes for all files accordingly.
Once all files have been run through the accept function (droppedFilesCounter == 0) and some feedback messages have been prepared the prepareFeedback function is called, which basically populates a jQuery <div> container with the cumulated content of dzCustomFeedback.
init: function() {
var myDropzone = this;
myDropzone.on("drop", function(event) {
if(typeof event.dataTransfer.files == 'object')
{
droppedFilesCounter = event.dataTransfer.files.length;
}
dzCustomFeedback = {};
jQuery('#dz-feedback').empty();
});
},
accept: function(file, done) {
/ * Erweiterung der vordefinierten accept Function * /
customTypeSelector = document.getElementById("selectUploadFolder");
var currentAcceptedFiles = customTypeAcceptedFiles[customTypeSelector.options[customTypeSelector.selectedIndex].value]
var currentFileExtension = file.name.split(".").pop()
droppedFilesCounter--;
if (typeof customTypeAcceptedFiles[customTypeSelector.options[customTypeSelector.selectedIndex].value] == "object"
&&
jQuery.inArray(currentFileExtension, currentAcceptedFiles["extensions"] ) >= 0) {
//accepted file
done();
}
else {
//Unaccepted file revert
this.removeFile(file);
if(typeof dzCustomFeedback["invalidFileTypes"] == "undefined")
{
dzCustomFeedback["invalidFileTypes"] = {
"msg": [
uploadDndConf["textElements"]["invalidFileTypesUploadFolder"].replace("{{uploadFolder}}", currentAcceptedFiles["label"])
, currentAcceptedFiles["extensions"].join()
]
, "type": "error"
, "filesIgnored": {} };
}
dzCustomFeedback["invalidFileTypes"]["filesIgnored"][file.name] = file;
done(this.options.dictInvalidFileType);
}
if(droppedFilesCounter == 0 && !jQuery.isEmptyObject(dzCustomFeedback))
{
prepareFeedback(dzCustomFeedback);
}
},

Dropzone remove all file except first file

Just simple ask, I have code like this on JavaScript on dropzone
addRemoveLinks: true,
maxFiles: 1,
init: function() {
this.on("maxfilesexceeded", function(file) {
swal("Error", "U just can upload 1 file", "warning");
});
}
Well is kind a work the file not upload if I have a file, but that file (not first one) still show even they not uploaded, I need to remove all file (not first one) automatic if they didn't upload or get alert. How can I did that???
You can call the removeFile() method, also if you want the thumbnail to show for a moment with the message you can add a timeout:
Dropzone.options.myAwesomeDropzone = {
maxFiles: 1,
dictMaxFilesExceeded: "U just can upload 1 file",
init: function () {
var myDropzone = this;
this.on("maxfilesexceeded", function(file) {
setTimeout(function() {
myDropzone.removeFile(file);
}, 3000);
});
},
};

Implement dropzone in mvc razor form

I have a mvc form with multiple fields that are calling custom edit views.
I need to implement dropzone instead of the standard file import control.
I cant figure out how to get the file names and pass them together with the dropzone. I am searching the internet for 2 days and no results.
The form looks like this:
#using (Html.BeginForm("contr", "action", new { themeid = ViewBag.ThemeId, #class = "dropzone"}, FormMethod.Post, new { #enctype = "multipart/form-data" }))
At the end I have an Edit view that contains the dropzone div:
<div id="fileInput" class="dropzone">
<div class="fallback">
<input name="files" type="file" multiple />
</div>
</div>
Function for the dropzone:
function initDropzone() {
new Dropzone('#fileInput', {
url: '#',
autoProcessQueue: false,
uploadMultiple: true,
addRemoveLinks: true,
autoDiscover: false,
parallelUploads: 100,
dictDefaultMessage: "Click or drop files to upload",
init: function () {
var myDropzone = this;
$('#submit-all').click(function (e) {
$(".dz-progress").show();
myDropzone.processQueue();
});
myDropzone.on('success', function () {
myDropzone.removeAllFiles();
//$('#name').val('');
});
myDropzone.on("sending", function (file, xhr, formData) {
formData.append("file", file); // Append all the additional input data of your form here!
});
myDropzone.on("addedfile", function (event) {
$(".dz-progress").hide();
});
}
});
As most examples suggest I call processQueue when submit is clicked, but the problem is that the controller action is called twice, once with the files but without the other models, and the next time with the models but without the files.
I can't use stopPropagation on submit because I call different views based on the logic in the action method.
The basic question is how I can take the files from dropzone and append them to form data.
Hidden fields does not work, I don't know why.
Any help would be appreciated.

Categories