I do not have much knowledge in javascript. I am trying to get and print file name in a input box after a successful upload event. I'm using plupload ui widget. the below script works fine, I can upload files but I cant get file name after the upload finishes. I have googled a lot but couldn't get it working.
here is the code I'm using..
// Initialize the widget when the DOM is ready
$(function() {
$("#uploader").plupload({
// General settings
runtimes : 'html5,flash,silverlight,html4',
url : 'upload.php',
// User can upload no more then 20 files in one go (sets multiple_queues to false)
max_file_count: 20,
chunk_size: '1mb',
filters : {
// Maximum file size
max_file_size : '10mb',
// Specify what files to browse for
mime_types: [
{title : "Image files", extensions : "jpg,gif,png"},
{title : "Zip files", extensions : "zip"}
]
},
// Rename files by clicking on their titles
rename: true,
// Sort files
sortable: true,
// Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
dragdrop: true,
prevent_duplicates: true,
// Views to activate
views: {
list: true,
thumbs: true, // Show thumbs
active: 'thumbs'
},
// Flash settings
flash_swf_url : 'js/Moxie.swf',
// Silverlight settings
silverlight_xap_url : 'js/Moxie.xap'
});
uploader.bind('FileUploaded' , function(up, file, response ) {
if ( (Uploader.total.uploaded + 1) == Uploader.files.length)
{
alert(File.name);
};
})
// Handle the case when form was submitted before uploading has finished
$('form').submit(function(e) {
var uploader = $('#uploader').plupload('getUploader');
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind('StateChanged', function() {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
$('form')[0].getlink();
}
});
uploader.start();
} else {
alert("You must have at least one file in the queue.");
}
return false; // Keep the form from submitting
});
});
You have a faulty conditional in your FileUploaded handler:
if ( (Uploader.total.uploaded + 1) == Uploader.files.length)
Why Uploader.total.uploaded + 1? It will never get fulfilled.
Also Plupload UI widget has it's own syntax for attaching handlers to the events.
// Subscribing to the events...
// ... on initialization:
$('#uploader').plupload({
...
viewchanged: function(event, args) {
// stuff ...
}
});
// ... or after initialization
$('#uploader').on("viewchanged", function(event, args) {
// stuff ...
});
Consider the following playground sample.
Related
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);
}
},
I am trying to make plupload work from the jsfiddle sample jsfiddle-plupload
but that is not working on my side, the statechange events if block is getting skipped below is code
function validClasses()
{
datas=[];
$('#uids li').each(function() {
var data = {
className: $(this).attr("id")
};
datas.push(data);
});
if(datas.length>0)
{
return true;
}else{
alert('error');
return false;
}
}
var uploadInitialized = false;
function plupload(){
var uploader = $("#uploader").pluploadQueue({
// General settings
runtimes: 'html5,html4',
url: 'fileUpload.htm',
max_file_size: '200mb',
chunk_size: '1mb',
unique_names: true,
multiple_queues: true,
multipart_params: {
"name": $("#name").val()
},
// Specify what files to browse for
filters: [
{
title: "Image files",
extensions: "jpg,gif,png,eps,jpeg,pdf,tiff,tif"},
{
title: "Zip files",
extensions: "zip"}
],
init: {
StateChanged: function(up) {
if (!uploadInitialized && up.state == plupload.STARTED) {
if (!validClasses()) {
up.stop();
} else {
uploadInitialized = true;
}
}
},
BeforeUpload: function(up, file) {
up.settings.multipart_params = {'name': $('#name').val()}
}
}
});
}
please note that in jsfiddle sample, the upload is just stopped, that is i can upload without adding files again. Where as on my side, the start upload button is getting disappeard, the file is in list but buttons disappear. and i am getting the upload status in place of buttons, i want the buttons to be there if upload is stopped also. I means in StateChanged i directly wrote up.stop() and that is also not working. Anyone please help. Thanks.
i am posting some json string, which i can see in alert also, but that is not getting posted, i am making tht string from DOM, instead when i manually make a jsonarray, its getting posted. below is the code, please check and tell the mistake.
function plupload(){
$("#uploader").pluploadQueue({
// General settings
runtimes : 'html5,gears,browserplus,silverlight,flash,html4',
url : 'uploads',
max_file_size : '10mb',
unique_names : false,
chunk_size: '2mb',
// Specify what files to browse for
filters : [
{title: "Image files", extensions: "jpg,gif,png"},
{title: "Zip files", extensions: "zip"}
],
resize: {width: 320, height: 240, quality: 90},
// Flash settings
flash_swf_url : 'plup/Moxie.swf',
// Silverlight settings
silverlight_xap_url : 'plup/Moxie.xap',
multipart_params: {'stringObj': JSON.stringify(datas), 'time': '2012-06-12'}
});
$("#uploader").pluploadQueue().bind('BeforeUpload', function(up, files) {
$('#uids li').each(function() {
var data = {
uid: $(this).text()
};
datas.push(data);
});
alert(JSON.stringify(datas));
});
}
plupload();
$('#clear').click(function(){
plupload();
});
there is bind beforeupload event. and i can see the json string in alert also, the var datas[] is declared above all the functions.
thanks and regards
k. I have done this to send data to server with multipart params of plupload. Solved now
$("#uploader").pluploadQueue().bind('BeforeUpload', function(up) {
$('#uids li').each(function() {
var data = {
uid: $(this).text()
};
datas.push(data);
});
up.settings.multipart_params =
{
'stringObj': JSON.stringify(datas)
};
alert(JSON.stringify(datas));
});
I am trying to use Blueimp / jQuery-File-Upload my project and I want to test the file extension because I only want to download photos
someone show me where and how I should configure blueimp / jQuery-File-Upload so I can do this
As stated in the documentation you can simply set the options to a regex for the file type like that:
$('#fileupload').fileupload('option', {
url: '//localhost/',
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'
}
]
});
I found this add method
So, here is my code for .gpx files:
$('#fileupload').fileupload({
// your fileupload options
add:function(e,data){
data.files.map(function(i){
if(i.type!='application/gpx+xml'){
alert('please upload only .gpx files');
}else{
data.submit();
}
}),
process: function(e,data){/* your process actions here */}
});
Your can use the method add for filter files:
var $input = $('#upload_input');
$input.fileupload({
fileInput: $input,
url: 'YOU_URL',
// Other options...
start: function(e, data) {
// Before start upload... Please wait...
},
add: function(e, data) {
types = /(\.|\/)(gif|jpe?g|png)$/i;
file = data.files[0]
if (types.test(file.type) || types.test(file.name)) {
data.submit();
} else {
// alert('Unfortunately, we don’t support that file type. Try again with a PNG, GIF, JPG');
return;
}
},
done: function(e, data) {
// After upload... alert('Done');
},
fail: function(e, data) {
// Error. Please try again later...
}
});
This is the code that is used to trigger Plupload in my Rails App:
<% content_for :deferred_js do %>
$("#uploader").pluploadQueue({
runtimes : 'gears,html5,flash,browserplus,silverlight,html4',
url : '/uploads.js',
//browse_button : 'pickfiles',
max_file_size : '10mb',
chunk_size : '2mb',
unique_names : false,
container: 'uploader',
autostart: true,
//RoR - make sure form is multipart
//multipart: true,
// Specify what files to browse for
filters : [
{title : "Image files", extensions : "jpg,gif,png,bmp"}
],
// PreInit events, bound before any internal events
preinit : {
UploadFile: function(up, file) {
up.settings.multipart_params = {"upload[stage_id]" : compv.steps.selectedStage.getID(), "authenticity_token" : compv.tools.csrf_token()};
}
},
// Post init events, bound after the internal events
init : {
FilesAdded: function(up, files) {
// Called when files are added to queue
up.start();
},
FileUploaded: function(up, file, info) {
// Called when a file has finished uploading
console.log('[FileUploaded] File:', file, "Info:", info);
info.responseText = info.response;
compv.updateStepView('upload', info);
$('tr[data-upload] td.selectable-step').each(function(index){
compv.steps.selectedUpload.primeUploadDisplay($(this));
});
},
Error: function(up, args) {
// Called when an error has occured
up.stop();
compv.tools.clientError();
}
},
// Flash settings
flash_swf_url : '/plupload/js/plupload.flash.swf',
// Silverlight settings
silverlight_xap_url : '/plupload/js/plupload.silverlight.xap'
});
compv.steps.selectedUpload.uploader = $('div#uploader').pluploadQueue();
//compv.steps.selectedUpload.uploader.init();
// Client side form validation
$('form#new_upload').submit(function(e) {
var uploader = $('#uploader').pluploadQueue();
// Validate number of uploaded files
if (uploader.total.uploaded == 0) {
// Files in queue upload them first
if (uploader.files.length > 0) {
// When all files are uploaded submit form
uploader.bind('UploadProgress', function() {
if (uploader.total.uploaded == uploader.files.length)
$('form').submit();
});
uploader.start();
} else
$('div#upload-empty-dialog').dialog("open");
e.preventDefault();
}
});
$('div#upload-empty-dialog').dialog({modal:true, autoOpen: false, minWidth: 325, buttons: { "Ok": function() { $(this).dialog("close"); } }});
$('div#upload-cancel-dialog').dialog({modal:true, autoOpen: false, minWidth: 325});
<% end %>
<div class="dialog" id="upload-empty-dialog" title="No Files">
<p>You must select files to upload first.</p>
</div>
<div class="dialog" id="upload-cancel-dialog" title="Cancel Uploading?">
<p>Do you want to stop uploading these images? Any images which have not been uploaded will be lost.</p>
</div>
Is there anything obvious that jumps out that could be causing this ?
Edit1: Btw, when I try this upload form - http://jsfiddle.net/Atpgu/1/ - the add files button fires for me on both Chrome & FF - so I suspect it has something to do with my JS, I just don't know what.
Edit2: This is what the definition of compv is. I know it's a bit verbose, and I was going to reduce it - but decided not to at the risk of removing something important.
var compv = {
exists: true,
tools: { exists: true,
csrf_param : null,
csrf_token : null},
comments: { exists: true,
updateView: null,
selectImage: null,
upvote:null,
downvote:null,
showVotes:null,
getUploadID: function(element){
return $(element).parents("li").attr("data-upload-id");
}},
steps: { exists: true,
selectFn:{},
selectedClass: "selected-step",
selectableClass: "selectable-step",
selectedClient: { element: null,
id: null,
stepType: "client",
ajaxSuccess: null },
selectedProject: { element: null,
id: null,
stepType: "project",
ajaxSuccess: null },
selectedStage: { element: null,
id: null,
stepType: "stage",
ajaxSuccess: null,
getID: function(){
return compv.steps.selectedStage.id;
},
displayCompare: function(){
window.open($(this).attr('data-url'), "_blank");
}},
selectedUpload: { element: null,
id: null,
stepType: "image",
primeUploadDisplay: null,
ajaxSuccess: null,
uploader: null,
noCloseDialog: false} }
};
Plupload is not rendering correctly for hidden elements, that is why it should be refreshed after shown.
In given example, after DIALOG is opened, there should be added few lines of code:
var uploader = $('#uploader').pluploadQueue();
uploader.refresh();
I noticed, that in chrome, it has problems to set z-index correctly for input container. To workaround that, just add another line after previous two:
$('#uploader > div.plupload').css('z-index','99999');
You can solve this problem with Chrome easier by setting the css of your browse_button (= Select Files Button) to a higher z-index (z-index:99999) !
Lucian
I know this is an old question but it seems that the z-index issue is still around in the later versions of plupload (1.5.2).
The problem is caused by code in plupload.html5.js which changes the z-index of the "Add Files" button specifically for Webkit browsers and in doing so breaks things:
zIndex = parseInt(plupload.getStyle(browseButton, 'z-index'), 10);
if (isNaN(zIndex)) {
zIndex = 0;
}
plupload.extend(browseButton.style, {
zIndex : zIndex
});
plupload.extend(inputContainer.style, {
zIndex : zIndex - 1
});
If you view the DOM you will see that style="z-index: 0;" is added to the #uploader_browser anchor element, and the div containing the "Add Files" button gets a z-index of -1 which effectively hides it behind the page (depending on your pages z-index of course).
To fix this I set the zIndex value in the file mentioned above to something higher than the page that the plupload div was being displayed on.
Deele's solution with css is good but little better is to do it this way:
$('#uploader > div.plupload input').css('z-index','99999');
That way hover of button will be not broken...