Plupload Automatically start upload when files added - javascript

When files are added i want to start the upload process automatically. I called the start function at the end of FilesAdded but it doesn't start the upload.
uploader.bind('FilesAdded', function(up, files) {
var str = "";
for (var i in files) {
str += '<div id="' + files[i].id + '">' + files[i].name + ' (' + plupload.formatSize(files[i].size) + ') <b></b></div>';
}
$('#filelist').html(str);
up.refresh();
up.start();
});
Here is my creation code
var uploader = new plupload.Uploader({
runtimes: 'html5,flash,silverlight',
autostart : true,
url: '<%= images_path %>',
max_file_size: '10mb',
multipart: true,
browse_button: "pickfiles",
container: "the-uploader",
drop_element : "drop-area",
multipart_params: {
'_http_accept': 'application/javascript',
'<%=request_forgery_protection_token%>': '<%=form_authenticity_token%>',
'<%=request.session_options[:key]%>': '<%=request.session_options[:id]%>'
},
filters: [
{title: "Images", extensions: "avi,jpg,jpeg,png,zip"}
],
});

Adding up.start() in your FilesAdded bind should start the upload when a file is added. I've gone down the route of calling my uploader like so (I had problems doing it the way you are trying to call it):
$(function() {
// Setup html5 version
$("#html5_uploader").pluploadQueue({
// General settings
runtimes : 'html5',
url : 'upload.php',
max_file_size : '10mb',
chunk_size : '1mb',
unique_names : true,
dragdrop : true,
multiple_queues : false,
multi_selection : false,
max_file_count : 1,
// Specify what files to browse for
filters : [
{title : "Text files", extensions : "txt"}
],
init : {
FilesAdded: function(up, files) {
up.start();
},
UploadComplete: function(up, files) {
$.each(files, function(i, file) {
// Do stuff with the file. There will only be one file as it uploaded straight after adding!
});
}
}
});
});

"Make sure you bind it after the init since it binds default handlers."
So your code:
uploader.bind('FilesAdded', function(up, files) {...});
after your
uploader.init();
more information

For me it didn't work your version but did work :
FilesAdded: function(up, files) {
setTimeout(function () { up.start(); }, 100);
},
So set a timer after 100 ms to execute the start.
I am using the jquery ui version while testing and got this error :
g("#" + l.id).position() is null
/js/plupload/js/jquery.ui.plupload/jquery.ui.plupload.js

I was also wanting same for me and found below way to do it.
A new way to automatically start file uploading after adding file is just need to set true to autostart property like below
$("#uploader").plupload({
.....
autostart: true,
.....
});

Just trigger the Start Upload button by this way
FilesAdded: function(up, files) {
$('#fileupload_start').click();
},
This will upload the file without waiting for 100 ms.

Related

Reset FilePond Input in Javascript

I have implemented Filepond uploaded in my page. When the user selects a file, I set that file on a html canvas for edits. However when the user wants to upload another file, filepond input retains last uploaded file.
I have tried FilePond.destroy(inputElement); after the file is successfully set on the canvas in the FilePond:addfile event.
$('.upload-file').filepond();
$.fn.filepond.registerPlugin(
FilePondPluginFileValidateType,
FilePondPluginFileValidateSize,
FilePondPluginImageResize,
FilePondPluginImageExifOrientation,
FilePondPluginImagePreview,
FilePondPluginImageTransform,
FilePondPluginImageCrop,
FilePondPluginImageValidateSize,
);
FilePond.setOptions({
labelIdle: 'Drag & Drop your file or <span class="filepond--label-
action"> Browse </span>',
maxFiles: 1,
allowDrop: true,
allowMultiple: false,
dropOnPage: true, //for page to work, element has to be false https://github.com/pqina/filepond/issues/113
dropOnElement: false,
labelTapToCancel: '', //we dont want to allow cancel
labelTapToUndo: '',
maxFileSize: intFileSizeInMB,
allowReplace: true,
allowRevert: false,
instantUpload: false
});
const pond = document.querySelector('.filepond--root');
pond.addEventListener('FilePond:addfile', e => {
console.log('File added', e.detail);
if (e.detail) {
if (e.detail.file && e.detail.file.file.name) {
SetFileOnCanvas(e.detail.file.file, e.detail.file.file.name);
const inputElement = document.querySelector('input[type="file"]');
FilePond.destroy(inputElement);
}
}
});
pond.addEventListener('FilePond:processfile', e => {
console.log('Process File COMPLETE', e.detail);
});
After a file is uploaded and set to Canvas the file upload input should be cleared and ready for another upload.
Working solution
var pond_ids = [];
if (pond.getFiles().length != 0) { // "pond" is an object, created by FilePond.create
pond.getFiles().forEach(function(file) {
pond_ids.push(file.id);
});
}
pond.removeFiles(pond_ids);
After upload file "Complete function"
you can do like this (simple example):
if (filePond.getFiles().length != 0) {
for (var i = 0; i <= filePond.getFiles().length - 1; i++) {
filePond.removeFile(filePond.getFiles()[0].id)
}
}
I know its too late but you can use
let filePond = FilePond.find(document.getElementById(filePondElementId));
if (filePond != null) {
//this will remove all files
filePond.removeFiles();
}
<script src="https://unpkg.com/filepond/dist/filepond.min.js"></script>
Assuming that you create your filepond instance through function create_pondProfile and your input has class filepond, in you filepond config in server block do like this:
server: {
url: '',
process: {
url: '/path/to/upload/',
headers: {'X-CSRF-TOKEN': csrf},
ondata: (formData) => {
return formData;
},
onload: (response) => {
FilePond.destroy(document.querySelector('.filepond'));
create_pondProfile('.filepond');
}
},
...
...
}
It will destroy current instance of filepond and creates new one after upload.

How to do override uploadifive method?

Please give me code example for override any method of uploadifive.
Here i have putted my js code, please have your look. i want to check duplicate file from backend. I have already method in controller.
If you give any sample for how i can override method then i can try ahead.
$('#file_upload').uploadifive({
'auto' : true,
'buttonText' : 'Select File',
'checkScript' : false,
'queueSizeLimit' : 10,
'fileSizeLimit' : 10737418240,
'dnd' : false,
'multi' : true,
'removeCompleted' : true,
'queueID' : 'queue',
'simUploadLimit' : 30,
'uploadLimit' : 30,
'overrideEvents' : ['onProgress'],
'uploadScript' : '/files/pending',
// Triggered for each file that is added to the queue
'onAddQueueItem' : function(file) {
console.log(file.name + "file that is added to the queue");
var folder = files.currentItemData();
this.data('uploadifive').settings.formData = {
'timestamp' : current_date_time(),
'authenticity_token' : token(),
'attachment[folder_id]' : folder.id,
'attachment[context_code]' : current_context_code(),
'attachment[language]' : uploadifive_language_code(),
'success_action_status' : "201",
//'attachment[duplicate_handling]': file.duplicate_handling,
};
},
// Triggered when a file is cancelled or removed from the queue
'onCancel' : function() {},
// Triggered when the server is checked for an existing file
'onCheck' : function() {},
// Triggered during the clearQueue function
'onClearQueue' : function() {},
// Triggered when files are dropped into the file queue
'onDrop' : function() {},
// Triggered when an error occurs
'onError' : function(file, fileType, data) {},
// Triggered if the HTML5 File API is not supported by the browser
'onFallback' : function() {},
// Triggered when UploadiFive if initialized
'onInit' : function() {},
// Triggered once when an upload queue is done
'onQueueComplete' : function(file, data) {},
// Triggered during each progress update of an upload
'onProgress' : function(file, e) {
if (e.lengthComputable) {
var percent = Math.round((e.loaded / e.total) * 100);
}
$('.uploadifive-queue-item').find('.fileinfo').html(' - ' + percent + '%');
$('.uploadifive-queue-item').find('.progress-bar').css('width', percent + '%');
},
// Triggered once when files are selected from a dialog box
'onSelect' : function(file) {
console.log(file.queued + ' files were added to the queue.');
return;
},
// Triggered when an upload queue is started
'onUpload' : function(file) {
console.log(file + ' files will be uploaded.');
file_select_done();
},
// Triggered when a file is successfully uploaded
'onUploadComplete' : function(file, data) {
res_data = JSON.parse(data);
$.ajaxJSON(res_data.success_url,'GET',{"authenticity_token" : authenticity_token},function(data) {
if (data && data["attachment"]){
var file_id = data["attachment"]["id"];
var file_name = data["attachment"]["display_name"];
generate_li(file_name, file_id);
qutaUpdate();
}
});
console.log('The file ' + file.name + ' uploaded successfully.');
},
// Triggered for each file being uploaded
'onUploadFile' : function(file) {
console.log('The file ' + file.name + ' is being uploaded.');
}
});});
I found answer of my above question: :)
$('#file_upload').uploadifive({
'overrideEvents' : ['onProgress','onCheck'],
});
I putted uploadifive method in array and now all my code calling here not uploadifive's code.
Thanks!

ExtJs: How to use plugin within defined component in MVC architecture?

Due to the lack of experience, I can't find how to activate an upload plugin in button component using MVC architecture.
When I used few files, this plugin works perfect.
But when I started to move to MVC direction, everything begin to fall apart.
Here is how I initialize the plugin:
Ext.Loader.setConfig( {
enabled: true,
paths: {
'Ext.ux.upload': 'ext-4.2.1.883/src/ux/upload/'
}
});
Ext.require([
....
'Ext.ux.upload.Button',
'Ext.ux.upload.plugin.Window',
.....
Here is the "old way" which worked perfect (button is situated on a panel, when you click it, the plugin upload window opens):
ObjectPhotosTab = Ext.create('Ext.Panel', {
disabled : true,
id : 'ObjectPhotosTab',
collapsible : true,
frame : true,
title : 'Photos',
items : [
//here goes button with upload plugin
Ext.create('Ext.ux.upload.Button', {
text : 'Select files',
id : 'ObjectPhotosUploadBtn',
SelectedObjectId : 0,
autoRender : true,
hidden : true,
plugins: [{
ptype : 'ux.upload.window',
title : 'Upload',
width : 320,
height : 350,
pluginId: 'pid'
}],
uploader: {
url : MainSiteUrl + 'getimages.php?a=a&Object=',
uploadpath : '/Root/files',
autoStart : true,
max_file_size : '2020mb',
statusQueuedText: 'Ready to upload',
statusUploadingText: 'Uploading ({0}%)',
statusFailedText: '<span style="color: red">Error</span>',
statusDoneText: '<span style="color: green">Complete</span>',
statusInvalidSizeText: 'File too large',
statusInvalidExtensionText: 'Invalid file type'
},
listeners: {
filesadded: function(uploader, files) {
console.log('filesadded');
return true;
},
.......,
scope: this
}
}),
Ext.getCmp('ImagesDataView') // other stuff
]
});
In my new application I have moved an upload button to the "view" directory (surely through controller) and put plugin params to initComponent like this:
Ext.define('crm.view.ObjectPhotosUploadBtn',{
extend: 'Ext.ux.upload.Button',
text : 'Select files',
id : 'ObjectPhotosUploadBtn',
alias : 'widget.ObjectPhotosUploadBtn',
SelectedObjectId : 0,
autoRender : true,
hidden : false,
initComponent: function() {
this.plugins = {
ptype : 'ux.upload.window',
title : 'Upload',
width : 320,
height : 350,
pluginId: 'pid'
};
this.uploader ={
// exactly the same stuff
};
this.listeners = {
// exactly the same stuff
};
this.callParent();
}
})
New defined button class is called from a panel like this:
ObjectPhotosTab = Ext.create('Ext.Panel', {
disabled : true,
id : 'ObjectPhotosTab',
collapsible : true,
frame : true,
title : 'Photos',
items : [
Ext.widget('ObjectPhotosUploadBtn'), // call button via widget
Ext.getCmp('ImagesDataView') // other stuff
]
});
Here is the header of file /ext-4.2.1.883/src/ux/upload/plugin/Window.js
/**#class Ext.ux.upload.plugin.Window
* #extends Ext.AbstractPlugin
* #author Harald Hanek (c) 2011-2012
* #license http://harrydeluxe.mit-license.org*/
Ext.define('Ext.ux.upload.plugin.Window', {
extend: 'Ext.AbstractPlugin',
alias: 'plugin.ux.upload.window',
requires: [ 'Ext.ux.statusbar.StatusBar',
'Ext.ux.statusbar.ValidationStatus' ],
constructor: function(config) {
var me = this;
Ext.apply(me, config);
me.callParent(arguments);
},
init: function(cmp) {
var me = this,
uploader = cmp.uploader;
cmp.on({
filesadded: {
......
Here is the header of file /ext-4.2.1.883/src/ux/upload/Button.js
/**#class Ext.ux.upload.Button
* #extends Ext.button.Button
* #author Harald Hanek (c) 2011-2012
* #license http://harrydeluxe.mit-license.org */
Ext.define('Ext.ux.upload.Button', {
extend: 'Ext.button.Button',
alias: 'widget.uploadbutton',
requires: ['Ext.ux.upload.Basic'],
disabled: true,
constructor: function(config) {
var me = this;
config = config || {};
Ext.applyIf(config.uploader, {
browse_button: config.id || Ext.id(me)
});
me.callParent([config]);
},
initComponent: function() {
var me = this,
e;
me.callParent();
me.uploader = me.createUploader();
......
The problem is that the button is created successfully but it does not do needed plugin action.
I see no errors in ff/chrome console also.
When I inspect "crm.view.ObjectPhotosUploadBtn" through the Illuminations ff plugin, I can see all needed plugin properties of this class.
Please help me to solve this question.
There is too much code for me to quote, but the problem lies in this snippet:
Ext.define('crm.view.ObjectPhotosUploadBtn',{
extend: 'Ext.ux.upload.Button',
...
initComponent: function() {
this.plugins = {
...
};
}
});
By the time initComponent is executed, the plugins have already been constructed and initialized in the constructor, and your initComponent overwrites all that.
What you need instead is to move the plugins blob into the class definition:
Ext.define('crm.view.ObjectPhotosUploadBtn', {
extend: 'Ext.ux.upload.Button',
...
plugins: [{
ptype : 'ux.upload.window',
title : 'Upload',
width : 320,
height : 350,
pluginId: 'pid'
}]
});
The same goes for uploader and listeners assignments.

Cancel uploads in onStatusChange

In our system we only allow uploads up to a specific number which can be done in multiple upload sessions. When the number of images in an upload session exceed this maximum number we are currently cancelling uploads in onStatusChange() instead of adjusting itemLimit:
thumbnailuploader = new qq.FineUploader({
element: document.getElementById('thumbnail-fine-uploader'),
template: "qq-simple-thumbnails-template",
request: {
endpoint: 'uploader/uploader.php'
},
thumbnails: {
placeholders: {
waitingPath: "uploader/waiting-generic.png",
notAvailablePath: "uploader/not_available-generic.png"
}
},
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png', 'bmp'],
itemLimit: 6
},
callbacks: {
onSubmit: function(id, fileName){
// console.log("submitting..." + id);
},
onStatusChange: function (id, oldStatus, newStatus) {
// This will check to see if a file that has been cancelled
// would equate to all uploads being 'completed'.
if(parseInt(galleryImages) + id + 1 > MaxUploads && newStatus !== qq.status.CANCELLED){
this.cancel(id);
return;
}
if (newStatus === qq.status.CANCELLED) {
check_done();
return;
}
},
onComplete: check_done,
onUpload: StartUpload
}
});
This seems to work well, but when switching on the debugger I get:
Error: [Fine Uploader 5.0.3] 1 is not a valid file ID to upload!
in
now: function(id) {
var name = options.getName(id);
if (!controller.isValid(id)) {
throw new qq.Error(id + " is not a valid file ID to upload!");
}
and a bunch of:
"[Fine Uploader 5.0.3] Caught exception in 'onStatusChange' callback - element is undefined"
Can this be fixed or are these messages harmless?
Thanks!

Fineuploader cancel upload after user response on file submit

I am trying to get user response on file submit to cancel or not to cancel file upload but it doesn't seem to stop file upload may be I am missing something pls suggest
onSubmit: function(id, name) {
doc_status = $('#doc_attach_status').val();
if (doc_status == "true" ) {
if(confirm("Please note, if you upload a new PDF, old one will be replaced") == false){
manualuploader.cancelAll(); // tried but does not work
cancelAll();// tried but does not work
cancel(id);// tried but does not work
$(this).cancelAll();// tried but does not work
}
}
},
And yes I am able to successfully upload files ......
And this is complete function I am using ...
var manualuploader = new qq.FineUploader({
callbacks : {
onComplete : function(id, name, response) {
}
},
element : $('#pdf-fine-uploader')[0],
request : {
endpoint : "/UploadPdf",
params : {
variant_id : $('#variant_id').val(),
}
},
multiple : false,
autoUpload : true,
text : {
uploadButton : '<i class="icon-plus icon-white"></i> Select File </br> Maximum upload size less than 2 MB'
},
validation : {
allowedExtensions : ['pdf', 'txt'],
//sizeLimit: 51200, // 50 kB = 50 * 1024 bytes
sizeLimit : 2097152//, // 2 MB = 2 * 1024 * 1024 bytes
//itemLimit : 6
},
callbacks : {
onSubmit: function(id, name) {
doc_status = $('#doc_attach_status').val();
// var answer = confirm("Please note, if you upload a new PDF, your current Tasting Notes PDF will be replaced");
if (doc_status == "true" ) {
if(confirm("Please note, if you upload a new PDF, your current Tasting Notes PDF will be replaced") == false){
manualuploader.cancelAll();
}
}
},
onComplete : function(id, fileName, responseJSON) {
if (responseJSON.success) {
$('.doc_link').html(responseJSON.docurl);
$('#doc_delete_link').addClass('icon-remove-sign');
$('.doc_description_head').show();
$('#doc_pdf_head').show();
$('.doc_description_div').show();
$('.description_save').show();
$('#doc_delete_link').show();
}
}
}
});
$('#triggerUpload').click(function() {
manualuploader.uploadStoredFiles();
});
});
Finally got very simple solution ...
just use
retrun true or false after getting user response ....
onSubmit: function(id, name) {
doc_status = $('#doc_attach_status').val();
if (doc_status == "true" ) {
if(confirm("Please note, if you upload a new PDF, old one will be replaced") == false){
retutn false;
}
}
},

Categories

Resources