plupload statechange even plupload.STARTED not working - javascript

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.

Related

How to add a process bar when you waiting for a response from the server

could someone help me with one problem? I want to add a process bar when you waiting for a response from the server (Django 3.x).
Step to reproduce:
On the page 'A' we have the form.
Enter data to form.
Submit POST request by clicking to button on the page 'A'.
Waiting for getting the result on the page 'A'.
Get the result on the page 'A'.
So, I want to add process bar after 4th and before 5th points on the page 'A'. When you will get the result on the page 'A' it should disappear.
Python 3.7
Django 3.x
You can use nprogress, it's a library used for progress bars. Use this inside the interceptor where you can config it for displaying only when request is in progress until finished.
There are lots of ways to do this. I think using jquery would be easier. Basically you just need to prevent submitting the page and do an Ajax request to server. something like
<script type='text/javascript'>
$(document).ready(function () {
$("form").submit(function (e) {
// prevent page loading
e.preventDefault(e);
$('#loadinAnimation').show();
// preapre formdata
$.ajax({
type: "yourRequestType",
url: "yourUrlEndpoint",
data: formdata,
success: function (data) {
$('#loadinAnimation').hide();
// do rest of the work with data
}
});
});
});
</script>
and show appropriate loading animation in your html part
<div id='loadinAnimation' style='display:none'>
<div>loading gif</div>
</div>
You can also do it using UiKit Library in Javascript on your Django Template Page.
Below code is when a file is Uploaded
In your template file (template.html)
<body>
..
<form>
<progress id="js-progressbar" class="uk-progress" value="0" max="100" hidden></progress>
...
<div class="uk-alert-danger uk-margin-top uk-hidden" id="upload_error" uk-alert></div>
...
</form>
</head>
<script type="text/javascript">
$(document).ready(function(){
var bar = document.getElementById('js-progressbar');
UIkit.upload('.js-upload-list', {
url: '',
name : "customer-docs",
params :{
"csrfmiddlewaretoken":"{{csrf_token}}"
},
method : "POST",
concurrent:1,
allow:'*.(csv|xlsx)',
beforeSend: function (environment) {
console.log('beforeSend', arguments);
// The environment object can still be modified here.
// var {data, method, headers, xhr, responseType} = environment;
},
beforeAll: function (args,files) {
console.log('beforeAll', arguments);
},
load: function () {
console.log('load', arguments);
},
error: function (files) {
console.log("---------------")
},
complete: function () {
console.log('complete', arguments);
},
loadStart: function (e) {
console.log('loadStart', arguments);
bar.removeAttribute('hidden');
bar.max = e.total;
bar.value = e.loaded;
},
progress: function (e) {
console.log('progress', arguments);
bar.max = e.total;
bar.value = e.loaded;
},
loadEnd: function (e) {
console.log('loadEnd', arguments);
bar.max = e.total;
bar.value = e.loaded;
},
completeAll: function (data) {
console.log('completeAll', arguments);
console.log('completeAll', data);
let redirect_loc = ""
setTimeout(function () {
bar.setAttribute('hidden', 'hidden');
}, 1000);
// This is the response from your POST method of views.py
data.responseText = JSON.parse(data.responseText)
if(data.responseText.status == 201){
// swal is another library to show sweet alert pop ups
swal({
icon: data.responseText.status_icon,
closeOnClickOutside: true,
text: data.responseText.message,
buttons: {
Done: true
},
}).then((value) => {
switch (value) {
case "Done":
window.location.href = ""
break;
}
});
}
else if(data.responseText.status == 500){
swal({
icon: data.responseText.status_icon,
closeOnClickOutside: true,
text: data.responseText.message,
buttons: {
Ok: true
},
}).then((value) => {
switch (value) {
case "Ok":
window.location.href = ""
break;
}
});
}
}
});
// This block of code is to restrict user to upload only specific FILE formats (below example is for CSV & XLSX files)
(function() {
var _old_alert = window.alert;
window.alert = function(e) {
console.log(e)
if(e.includes("csv|xlsx") || e.includes("Invalid file type")) {
$("#upload_error").html("Invalid file format. Valid formats are CSV, XLSX").removeClass('uk-hidden')
}else if(e.includes("Internal Server Error")) {
$("#upload_error").html("Internal Server Error Kindly upload Documents again").removeClass('uk-hidden')
}
else {
_old_alert.apply(window,arguments);
$("#upload_error").addClass('uk-hidden').html("")
}
};
})();
});
</script>
On your views.py you can do your computation and once done, you can return a response like below
resp_json = {
"status" : 201,
"status_icon" : "success",
"url" : "/",
"message": message
}
return HttpResponse(json.dumps(resp_json))
For more info on SWAL (Sweet Alerts), visit https://sweetalert.js.org/guides/

How to get/print file name after successful upload in plupload ui

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.

Extjs not able to upload file second time when it was already uploaded

I have a strange behavior of extjs file upload.
The file upload defined as:
items: [{
xtype: 'filefield',
itemId: 'uploadandsign',
buttonText: NG.getLabel('browse'),
buttonOnly: true,
hideLabel: true,
width: 100
}]
If the file uploading is success I show successful label on the screen with remove "X" button:
onOpenFileBrowserChange: function (filefield, newValue, oldValue, eOpts) {
var me = this,
form = filefield.up('form').getForm(),
infoBox = invoiceorigin.down('#fileuploadinfoplaceholder'),
fileDescription,
secondfilefield,
customerFileName = newValue.replace(/^.*[\\\/]/, ''),
draft = me.getDraft(),
isSigned = true,
files = draft.files();
if (filefield.itemId === 'uploadandsign') {
isSigned = false;
secondfilefield = invoiceorigin.down('#uploadnosign');
fileDescription = 'File system, Unsigned';
}
secondfilefield.disable();
if (form.isValid()) {
form.submit({
url: NG.getLatestApiPath('WebInvoice', 'UploadInvoiceFile'),
waitMsg: NG.getLabel('webinvoiceInvoiceOriginUploadingFile'),
success: function (fp, o) {
if (o.result.success) {
var file = o.result.file;
files.add({
fileName: file.fileName,
createDate: file.createDate,
isAttachment: false,
isSigned: isSigned,
fileOrigin: fileDescription,
customerFileName: customerFileName,
invoiceFileOrigin: 'Local'
});
filefield.disable();
infoBox.removeAll();
infoBox.add(Ext.create('NG.view.webinvoice.InformationBox', {
data: {
closable: true,
icon: true,
iconCls: 'n-pdf-icon',
content: '<div class="n-text-overflow" style="width:145px;">' + fileDescription + '<br/>' + customerFileName + '</div>'
}
}));
}
else {
}
},
failure: function (form, action) {
}
});
}
return false;
},
Then if I remove the file from #infobox, the reset() function called:
onRemoveFileClick: function (view) {
var me = this,
invoiceorigin = view.up('invoiceorigin'),
uploadNoSignBtn = invoiceorigin.down('#uploadnosign'),
uploadAndSignBtn = invoiceorigin.down('#uploadandsign'),
infoBox = invoiceorigin.down('#fileuploadinfoplaceholder'),
draft = me.getDraft(),
files = draft.files(),
pagemanager = view.up('webinvoicepagemanager'),
invoiceFilePlace = files.findExact('isAttachment', false);
me.deleteFileConfirmReject(
NG.getLabel('webinvoiceInvoiceOriginDeleteInvoiceFileTitle'),
NG.getLabel('webinvoiceInvoiceOriginDeleteInvoiceFileMsg'),
function (buttonId, text, opt) {
if (buttonId == 'yes') {
infoBox.removeAll();
if (invoiceFilePlace > -1) {
files.removeAt(invoiceFilePlace);
}
me.fillInvoiceOriginStep(pagemanager);
uploadNoSignBtn.reset();
uploadAndSignBtn.reset();
uploadNoSignBtn.enable();
uploadAndSignBtn.enable();
}
});
}
After this action if I will choose the same file.... nothing happens with page... no any change event fired on the page.. However if I choose different file the behavior is OK.
In the ExtJS documentation said that the reset() function have to clear previous files uploads... however it does not helps.
Is any body met such file upload ExtJS behaivour and could help with this issue?
Thanks a lot.
What I tried and worked quite good was to get the file from the form with a typical JS document.getElementsByName('[name you gave]'); and it got perfectly the file uploaded without mattering in wich execution you are in.
Hope it helps.

plupload data showing null in post

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));
});

filter files in Blueimp/ jQuery-File-Upload

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...
}
});

Categories