I'm using ajax file uploader on my pages.
https://github.com/blueimp/jQuery-File-Upload
I'm using one control for image uploading and another for file uploading and both are on the same page.
I've added the validation to check the file type in both of the file uploaders but when I drag and drop resume on my file uploader then it will catch the image uploader event.
I want to disable the functionality of drag and drop for image uploader so it will not trigger when i drag my resume.
Here's my code,
$(function () {
var userId = $("#CandidateProfile_user_id").val();
var url = 'index.php?r=fileUpload/uploadResume';
$('#resumeUpload').fileupload({
add: function(e, data) {
var uploadErrors = [];
var acceptFileTypes = /^document\/(doc|docx)$/i;
var fileName = data.originalFiles[0].name;
var fileExtension = fileName.split('.')[1];
if(fileExtension.toLowerCase() != "doc" && fileExtension.toLowerCase() != "docx") {
uploadErrors.push('Not an accepted file type');
}
// if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
// uploadErrors.push('Not an accepted file type');
// }
if(data.originalFiles[0]['size'].length && data.originalFiles[0]['size'] > 5000000) {
uploadErrors.push('Filesize is too big');
}
if(uploadErrors.length > 0) {
alert(uploadErrors.join("\n"));
} else {
data.submit();
}
},
url: url,
dataType: 'json',
formData: {userId : userId},
done: function (e,data) {
onFileUploaded(data.result.fileName,data.result.filePath);
//Update the pic
// $("#userPic").attr('src',data.result.imagePath);
//set the image name
// $("#CandidateProfile_image_name").val(data.result.imageName);
//console.log(data);
},
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
Thanks,
Faisal Nasir
You can disable drag & drop by setting the dropZone option to null.
$('#resumeUpload').fileupload({
dropZone: null,
add: function(e, data) {
Related
I have a drag and drop container for uploading images. Something like the option that stackoverflow has in the editor. As you know, it works in two ways:
drag and drop an image
click on the container and then a window will be opened to choose an image
Now I'm exactly doing something like that:
// click
$('.upload_image').on('change', function () {
file = $(this)[0].files;
frm = $(this).closest('form');
addImageToInput();
return false;
});
// drag and drop
$(".container").on('drop dragdrop', function (e) {
file = e.originalEvent.dataTransfer.files;
frm = $(this).closest('form');
addImageToInput();
return false;
});
Also I have one more function for making a preview:
function addImageToInput() {
if ( file !== "" || frm !== "" ) {
let uploadFormData = new FormData(frm[0]);
uploadFormData.append("imageToUpload", file[0]);
readURL(frm.find(".upload_image")[0]);
formData = uploadFormData;
} else {
alert('something went wrong');
}
}
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$('.modal-dropzone-img').html("<img src='" + e.target.result + "' class='upload_image_preview_img'/>");
}
reader.readAsDataURL(input.files[0]);
}
}
Anyway, the preview part works well when I attach an image by using "click" (browse) the image, and the preview part doesn't word (even no error throws) when I use drag and drop approach.
After some tests, I figured out, these aren't equal:
file = $(this)[0].files; // click approach
file = e.originalEvent.dataTransfer.files; // drag and drop approach
Any idea how can I make them equal? (in other word, I have to make the second one like the first one, because the first one is the working one)
I have modified the readURL method little bit to accept a file only, it can be drag drop or uploaded . Also addImageToInput() is changed accordingly
function addImageToInput() {
if ( file !== "" || frm !== "" ) {
let uploadFormData = new FormData(frm[0]);
uploadFormData.append("imageToUpload", file[0]);
readURL(file[0]);
formData = uploadFormData;
} else {
alert('something went wrong');
}
}
function readURL(input) {
if (input) {
var reader = new FileReader();
reader.onload = function(e) {
$('.modal-dropzone-img').html("<img src='" + e.target.result + "' class='upload_image_preview_img'/>");
}
reader.readAsDataURL(input);
}
}
here is a working fiddle
https://jsfiddle.net/153dp05q/
Is there any possibility that the multiple files will be uploaded one by one using dropzone.js. The following is a custom dropzone config script.
Dropzone.options.myDropzone = {
autoProcessQueue: false,
parallelUploads: 10,
addRemoveLinks:true,
init: function () {
var submitButton = document.querySelector("#submit-all");
myDropzone = this; // closure
submitButton.addEventListener("click", function () {
if(myDropzone.getQueuedFiles().length === 0)
{
alert("Please drop or select file to upload !!!");
}
else{
myDropzone.processQueue(); // Tell Dropzone to process all queued files.
}
});
},
url: "upload.php"
};
Right now, it uploads all files at a time which are all in the process queue. Since, the upload file size will be bigger, all files have to upload one by one. please help to short out the same.
I used this for uploading files one by one.
Hope this helps.
If you want the complete code according to your functions let me know.
startUpload() is called when customer confirms upload of files.
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("#uploadModal", {
url: "upload.php",
paramName: "file_upload",
maxFilesize: 1024,
maxFiles: 200,
autoProcessQueue: false
});
function startUpload(){
for (var i = 0; i < myDropzone.getAcceptedFiles().length; i++) {
myDropzone.processFile(myDropzone.getAcceptedFiles()[i]);
}
}
myDropzone.on('success', function(file, result) {
try {
result = JSON.parse(result)
if (!result.error) {
if(myDropzone.getQueuedFiles().length === 0 && myDropzone.getUploadingFiles().length === 0){
$("#uploadModal"). modal('hide');
myDropzone.removeAllFiles(true) ;
}
}
//TODO -
} catch (e) {
//TODO -
}
});
You need to set autoProcessQueue to true and parallelUploads to 1.
Setting autoProcessQueue to true tells dropzone to automatically process the queue. Setting parallelUploads to 1 tells dropzone to only upload one file at a time from the queue.
Dropzone.options.myDropzone = {
autoProcessQueue: true,
parallelUploads: 1,
addRemoveLinks:true,
init: function () {
var submitButton = document.querySelector("#submit-all");
myDropzone = this; // closure
submitButton.addEventListener("click", function () {
if(myDropzone.getQueuedFiles().length === 0)
{
alert("Please drop or select file to upload !!!");
}
else{
myDropzone.processQueue(); // Tell Dropzone to process all queued files.
}
});
},
url: "upload.php"
};
I'm struggling with the plugin JQuery-File-upload.
I would like to divide the upload process in two steps.
Step1 - when a file is selected in the input[type=file], I would
like to test its type and its size. The only accepted files should be
image files with a size < 4MB.
If the file does not match with these constraints a popup is displayed with an error message.
If the file is OK I display the name of the file in the input[type=text]
Step2 - when the user click on the button "OK", the upload of the
file start
I have the following code
$('#file-img').fileupload({
dataType: 'json',
autoUpload: false,
formData: {type: 'businessPicture'},
add: function (e, data) {
var uploadErrors = [];
var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
uploadErrors.push('Not an accepted file type');
}
if(data.originalFiles[0]['size'].length && data.originalFiles[0]['size'] > 4000000) {
uploadErrors.push('File size is too big');
}
if(uploadErrors.length > 0) {
alert(uploadErrors.join("\n"));
} else {
$.each(data.files, function (index, file) {
$("#txt-file-img").val(file.name);
});
//I COMMENT THIS LINE because if I do not, the upload start here.
//data.submit();
}
},
done: function (e, data) {
$("#output").html('<p class="valid">SUCCESS!</p>');
$.each(data.result.files, function (index, file) {
$("#preview-picture").css("max-width","160px");
$("#preview-picture").css("max-height","150px");
$("#preview-picture").attr("src",file.url+'#'+ new Date().getTime());
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#upload-progress .bar').css(
'width',
progress + '%'
).text(
progress + '%'
);
},
fail: function (e, data) {
$("#output").html('<p class="error">FAIL!</p>');
}
});
});
I don't understand most of the example provided on the Plugin website.
With the code above, the control (size & type) are OK but I don't know how to start the upload only after clicking on the button.
According to you what is the best way to manage this behaviour?
Thanks a lot
OK it's pretty easy. I just have to bind the click event on the button with the action data.submit directly under the event add of the instance $('#file-img').fileupload().
$('#file-img').fileupload({
dataType: 'json',
autoUpload: false,
formData: {type: 'businessPicture'},
add: function (e, data) {
var uploadErrors = [];
var acceptFileTypes = /^image\/(gif|jpe?g|png)$/i;
if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
uploadErrors.push('Not an accepted file type');
}
if(data.originalFiles[0]['size'].length && data.originalFiles[0]['size'] > 4000000) {
uploadErrors.push('File size is too big');
}
if(uploadErrors.length > 0) {
alert(uploadErrors.join("\n"));
} else {
$.each(data.files, function (index, file) {
$("#txt-file-img").val(file.name);
});
$("#btn_add_valid").on('click',function () {
data.submit();
});
}
},
//The rest of the function....
I am a bit stuck here and I need help..
I am trying to make drag and drop file upload in my website, I have started from scratch since I could not find any plugin that will fit my needs.
this is what I have so far:
File Drop detection:
var dropzone = document.getElementById('holder');
dropzone.ondragover = function(){
this.className = 'well pull-left display-ex-pic drag_hover';
return false;
}
dropzone.ondragleave = function(){this.className = 'well pull-left display-ex-pic'; return false;}
dropzone.ondrop = function(e){
e.preventDefault();
this.className = 'well pull-left display-ex-pic';
readURLs(e.dataTransfer.files);//display the pictures
images = e.dataTransfer.files;
images_obj = e.dataTransfer;
}
submitting the form through AJAX:
formImages = new FormData();
var status = $('#status');
$('#image_upload').hide();
$('form').ajaxForm({
beforeSend: function() {
$('#image_upload').show();
$('#math li .mathquill-editable').each(function() {
a = $('#math-text').val();
$('#math-text').val(a + $(this).mathquill('latex') + '[{line}]');
});
for (var x = 0; x < images.length; x = x + 1) {
formImages.append(images[x].fileName, images[x]);
}
},
data: {'files[]': formImages},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
$('#image_upload').attr('aria-valuenow', percentComplete).css('width', percentComplete + '%').html(percentComplete + '%');
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
Now my problem is that after the user drops the files the files get into a files array using e.dataTransfer.files and then I want to submit those files with a progress bar along with all of the form data using the "jQuery Form Plugin" from here http://malsup.com/jquery/form/.
Does anyone know how is it possible to send files using the "jQuery Form Plugin" manually?
I just happen to found this plugin and it works perfectly in very short time of implementation.
http://www.dropzonejs.com/#installation
Basically:
Include the plugin
Include the HTML
Code your File
Receiver at server side ( example included in the URL )
Adjust
CSS.
==== UPDATED QUESTION ====
I have control over onComplete state. That's not the case. The problem is that I don't know how to remove currently uploaded item's Progress Bar. Pls, check the screenshot.
I am using a jQuery plugin for multiupload with the support of HTML5 File API located on this website named damnUploader.
File upload works fine, but I'm stuck at the point where I need to hide the uploading progress bar once the upload is finished, but do not know how to do it without any special key to tell to remove progress bar from that element.
==== UPDATED QUESTION ====
To clarify my question, here is a screenshot. 5th and 6th images are at the uploading state. 6th image is about to be finished, so once it's successfully uploaded, I want to hide that progress bar which is below that image, but without touching the other progress bars on the other items.
Here is the javascript code (just search the function where is console.log(this._id); line:
var announcements = function () {
/*** ******************** ***/
/*** 1.1 MAIN INIT METHOD ***/
function _init() {
// Main inits on document ready state
}
/*** ********************* ***/
/*** 1.2 PRIVATE FUNCTIONS ***/
function _form_upload(){
// Main form for fallbacks
var $form_form = $('#form');
// Standard input file
var $form_file_input = $('#file_uploader');
// File POST field name (for ex., it will be used as key in $_FILES array, if you using PHP)
var $form_file_fieldName = 'image-file';
// Upload url
var $form_file_url = '/announcements/form_file_upload/' + $form_file_fieldName;
// List of available thumbnail previews based on selected files
var $form_file_list = $('#form_file_list');
// File upload progress
var $form_file_progress = $('#form_file_progress');
// Settings
var $form_file_autostartOn = true;
var $form_file_previewsOn = true;
// Misc
var isImgFile = function(file) {
return file.type.match(/image.*/);
};
var imagesCount = $form_file_list.length + 1;
var templateProgress = $form_file_list.find('div.progress').remove().wrap('<div/>').parent().html()
var template = $form_file_list.html()
// File uploader init
$form_file_input.damnUploader({
// URL of server-side upload handler
url: $form_file_url,
// File POST field name
fieldName: $form_file_fieldName,
// Container for handling drag&drops (not required)
dropBox: $('html'),
// Expected response type ('text' or 'json')
dataType: 'JSON',
// Multiple selection
multiple: false
});
// Creates queue table row with file information and upload status
var createRowFromUploadItem = function(ui) {
var $row = $('<div class="col-xs-4"/>').appendTo($form_file_list);
var $progressBar = $('<div/>').addClass('progress-bar progress-bar-success').css('width', '0%').attr('aria-valuemin', 0).attr('aria-valuemax', 100);
var $pbWrapper = $('<div/>').addClass('progress').append($progressBar);
// Defining cancel button & its handler
/*
var $cancelBtn = $('<a/>').attr('href', 'javascript:').append(
$('<span/>').addClass('glyphicon glyphicon-remove')
).on('click', function() {
var $statusCell = $pbWrapper.parent();
$statusCell.empty().html('<i>cancelled</i>');
ui.cancel();
console.log((ui.file.name || "[custom-data]") + " canceled");
});
*/
// Generating preview
var $preview;
if ($form_file_previewsOn) {
if (isImgFile(ui.file)) {
// image preview (note: might work slow with large images)
$preview = $('<img/>').attr('width', 120);
ui.readAs('DataURL', function(e) {
$preview.attr('src', e.target.result);
});
} else {
// plain text preview
$preview = $('<i/>');
ui.readAs('Text', function(e) {
$preview.text(e.target.result.substr(0, 15) + '...');
});
}
} else {
$preview = $('<i class="fa fa-image"></i>');
}
// Constructing thumbnails markup
$('<div class="thumbnail"/>').append($preview).appendTo($row);
$row.find('.thumbnail').append('<button type="button" name="formImageRemove" value="imageRemove" class="btn btn-danger btn-xs" role="button" />');
$row.find('.thumbnail').prepend(loading);
$row.find('.uploading').append($pbWrapper);
$row.find('button').append('<i class="fa fa-fw fa-trash-o" />');
return $progressBar;
};
// File adding handler
var fileAddHandler = function(e) {
// e.uploadItem represents uploader task as special object,
// that allows us to define complete & progress callbacks as well as some another parameters
// for every single upload
var ui = e.uploadItem;
var filename = ui.file.name || ""; // Filename property may be absent when adding custom data
// We can replace original filename if needed
if (!filename.length) {
ui.replaceName = "custom-data";
} else if (filename.length > 14) {
ui.replaceName = filename.substr(0, 10) + "_" + filename.substr(filename.lastIndexOf('.'));
}
// Show info and response when upload completed
var $progressBar = createRowFromUploadItem(ui);
ui.completeCallback = function(success, data, errorCode) {
// Original filename
// console.log((this.file.name || "[custom-data]"));
if (success) {
// Add animation class for fadeout
$(this).find('.loading').addClass('animated fadeOutDown');
console.log(this._id);
console.log(ui);
// Add some data to POST in upload request once upload finished and new filename retrieved
ui.addPostData($form_form.serializeArray()); // from array
ui.addPostData('images[]', JSON.parse(data).file_name); // .. or as field/value pair
} else {
console.log('uploading failed. Response code is:', errorCode);
}
};
// Updating progress bar value in progress callback
ui.progressCallback = function(percent) {
$progressBar.css('width', Math.round(percent) + '%');
};
// To start uploading immediately as soon as added
$form_file_autostartOn && ui.upload();
};
var loading = function(){
return '<div class="loading">\n\t<div class="uploading animated fadeInUp">\n\t\t<img src="/assets/img/loaders/ajax-loader.gif" />\n\t</div>\n</div>';
}
// File Uploader events
$form_file_input.on({
'du.add' : fileAddHandler,
'du.limit' : function() {
console.error("File upload limit exceeded!");
},
'du.completed' : function() {
console.info('******');
console.info("All uploads completed!");
}
});
}
/*** ************************************************** ***/
/*** 1.3 MAKE PRIVATE FUNCTIONS ACCESSIBLE FROM OUTSIDE ***/
return {
init: function () {
_init();
},
form_upload:function(){
_form_upload();
}
};
}();
$(document).ready(function () {
announcements.init();
});
Make a custom event and trigger it with Jquery:
$( "#hide_loading" ).on( "done", function() {
( "#hide_loading" ).animate({
opacity: 0
}, 5000);
});
if ( success ) {
$( ".hide_loading").trigger( "loadingfade" );
}
and if you completely want to remove it from the DOM structure after the animation:
$( "#hide_loading" ).on( "loadingfade", function() {
$( ".hide_loading" ).animate({
//put animations here (don't forget cross browser compatibility)
opacity: 0,
}, 5000, function() { //this function is called when the animation is completed
$( "#hide_loading" ).remove();
});
});
(now just add the class hide_loading to your loading elements)