Same file get download having multiple file - download

I am trying to download files one by one using angular js. When I click first file. It downloads. If click next file it downloads the same first file. Both the files are placed in the same
I had approached some people but of not use as they are downloading only 1 file
<a id="tbFileExport" style="display: none" href="{{repairEstimate.filePath}}/repairEstimate.fileName}}" download="{{repairEstimate.fileName}}"></a>
<div ng-if="repairEstimate.estimateRepairNo!=''" style="padding-top: 9px;"> <a data-ng-click="downloadFile()" style="color: green">{{repairEstimate.fileName}}</a>
In angularjs
$scope.downloadFile = function() {
$("#tbFileExport").bind('click', function() {
});
$('#tbFileExport').simulateClick('click');
}
$.fn.simulateClick = function() {
return this.each(function() {
if ('createEvent' in document) {
var doc = this.ownerDocument, evt = doc
.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true,
doc.defaultView, 1, 0, 0, 0, 0, false,
false, false, false, 0, null);
this.dispatchEvent(evt);
} else {`enter code here`
this.click();
}
});

Related

Dropzone showing the V&X icons below the drop box

My Flask project with Dropzone implementation dont show the file upload progress bar but rather both the 'V' and 'X' icons for each file, like this (the 'v' and 'x' icons are bearly visible below the file name):
, and they appear below the drop box, together with the file name and size, instead of inside the drop box. The files gets uploaded though, but the behaviour is undesired. Has anybody encountered the same problem?
HTML part:
<form id="myProjFileUploadForm" method="post" enctype="multipart/form-data" action="{{ url_for('projects.projects_file_upload') }}">
...
<div id="myFileDropContainer" class="dropzone dz-clickable" style="visibility: hidden">
<div class="dz-default dz-message">
<button class="dz-button" type="button">
Drop files here to upload.
</button>
</div>
</div>
...
</form>
script part:
Dropzone.autoDiscover = true;
myDropzone = new Dropzone("#myProjFileUploadForm", {
autoQueue: true,
clickable: ".dropzone",
paramName: 'file',
url: '/upload',
myFileDropContainer: "#myFileDropContainer",
chunking: true,
forceChunking: true,
retryChunks: true,
retryChunksLimit: 10,
maxFilesize: 2025, // The max file size in Mbytes that is allowed to be uploaded
chunkSize: 10000000, // The chunk size in bytes
autoProcessQueue: true,
timeout: 180000000,
maxFiles: 500000
});
// The function that is invoced when files are dropped in
myDropzone.on("complete", function (file) {
let sStatus = new String(file.status);
let objThisFile = file
sStatus = sStatus.trim();
let sFileName = new String(file.name);
let sLastModifiedDate = new String(file.lastModifiedDate);
let sSize = new String(file.size);
const myObjFile = {
FileName: sFileName, LastModDate: sLastModifiedDate, Size: sSize
}
if (sStatus == 'success') {
$.ajax({
"url": "{{ url_for('projects.save_file_info_to_database') }}",
"type": 'POST',
"data": JSON.stringify(myObjFile),
"contentType": "application/json",
"dataType": 'json',
success: function (response) {
bErr = response.result;
if (bErr) {
objThisFile.status = 'error'
let sErr = response.msg.toString().trim();
if (sErr.length > 0) {
//alert(sErr);
}
}
else {
myDrawFileTable();
}
}
})
}
else {
let sErr = "The following file failed to upload: " + sFileName;
//alert(sErr);
}
});

Invalid argument supplied for foreach() using laravel 7 [duplicate]

I have a lot of problem to upload multiple images using AJAX. I write this code:
HTML
<form id="upload" method="post" enctype="multipart/form-data">
<div id="drop" class="drop-area">
<div class="drop-area-label">
Drop image here
</div>
<input type="file" name="file" id="file" multiple/>
</div>
<ul class="gallery-image-list" id="uploads">
<!-- The file uploads will be shown here -->
</ul>
</form>
<div id="listTable"></div>
jQuery/AJAX
$(document).on("change", "input[name^='file']", function(e){
e.preventDefault();
var This = this,
display = $("#uploads");
// list all file data
$.each(This.files, function(i, obj){
// for each image run script asynchronous
(function(i) {
// get data from input file
var file = This.files[i],
name = file.name,
size = file.size,
type = file.type,
lastModified = file.lastModified,
lastModifiedDate = file.lastModifiedDate,
webkitRelativePath = file.webkitRelativePath,
slice = file.slice,
i = i;
// DEBUG
/*
var acc = []
$.each(file, function(index, value) {
acc.push(index + ": " + value);
});
alert(JSON.stringify(acc));
*/
$.ajax({
url:'/ajax/upload.php',
contentType: "multipart/form-data",
data:{
"image":
{
"name":name,
"size":size,
"type":type,
"lastModified":lastModified,
"lastModifiedDate":lastModifiedDate,
"webkitRelativePath":webkitRelativePath,
//"slice":slice,
}
},
type: "POST",
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
// Check if upload property exists
if(myXhr.upload)
{
// For handling the progress of the upload
myXhr.upload.addEventListener("progress",progressHandlingFunction, false);
}
return myXhr;
},
cache: false,
success : function(data){
// load ajax data
$("#listTable").append(data);
}
});
// display progress
function progressHandlingFunction(e){
if(e.lengthComputable){
var perc = Math.round((e.loaded / e.total)*100);
perc = ( (perc >= 100) ? 100 : ( (perc <= 0) ? 0 : 0 ) );
$("#progress"+i+" > div")
.attr({"aria-valuenow":perc})
.css("width", perc+"%");
}
}
// display list of files
display.append('<li>'+name+'</li><div class="progress" id="progress'+i+'">'
+'<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">'
+'</div></div>');
})(i);
});
});
I've tried a various versions and I never succeed to send multiple data through ajax. I have tried in this way what you see above, and now I get only POST informations. I understand why i get POST but I need to send FILES information and I do not know where I'm wrong.
I not work the first time with ajax and often use it for most projects but I have never used to send multiple files and that bothering me now.
Thanks!
Try utilizing json to upload , process file object
html
<div id="drop" class="drop-area ui-widget-header">
<div class="drop-area-label">Drop image here</div>
</div>
<br />
<form id="upload">
<input type="file" name="file" id="file" multiple="true" accepts="image/*" />
<ul class="gallery-image-list" id="uploads">
<!-- The file uploads will be shown here -->
</ul>
</form>
<div id="listTable"></div>
css
#uploads {
display:block;
position:relative;
}
#uploads li {
list-style:none;
}
#drop {
width: 90%;
height: 100px;
padding: 0.5em;
float: left;
margin: 10px;
border: 8px dotted grey;
}
#drop.hover {
border: 8px dotted green;
}
#drop.err {
border: 8px dotted orangered;
}
js
var display = $("#uploads"); // cache `#uploads`, `this` at `$.ajax()`
var droppable = $("#drop")[0]; // cache `#drop` selector
$.ajaxSetup({
context: display,
contentType: "application/json",
dataType: "json",
beforeSend: function (jqxhr, settings) {
// pre-process `file`
var file = JSON.parse(
decodeURIComponent(settings.data.split(/=/)[1])
);
// add `progress` element for each `file`
var progress = $("<progress />", {
"class": "file-" + (!!$("progress").length
? $("progress").length
: "0"),
"min": 0,
"max": 0,
"value": 0,
"data-name": file.name
});
this.append(progress, file.name + "<br />");
jqxhr.name = progress.attr("class");
}
});
var processFiles = function processFiles(event) {
event.preventDefault();
// process `input[type=file]`, `droppable` `file`
var files = event.target.files || event.dataTransfer.files;
var images = $.map(files, function (file, i) {
var reader = new FileReader();
var dfd = new $.Deferred();
reader.onload = function (e) {
dfd.resolveWith(file, [e.target.result])
};
reader.readAsDataURL(new Blob([file], {
"type": file.type
}));
return dfd.then(function (data) {
return $.ajax({
type: "POST",
url: "/echo/json/",
data: {
"file": JSON.stringify({
"file": data,
"name": this.name,
"size": this.size,
"type": this.type
})
},
xhr: function () {
// do `progress` event stuff
var uploads = this.context;
var progress = this.context.find("progress:last");
var xhrUpload = $.ajaxSettings.xhr();
if (xhrUpload.upload) {
xhrUpload.upload.onprogress = function (evt) {
progress.attr({
"max": evt.total,
"value": evt.loaded
})
};
xhrUpload.upload.onloadend = function (evt) {
var progressData = progress.eq(-1);
console.log(progressData.data("name")
+ " upload complete...");
var img = new Image;
$(img).addClass(progressData.eq(-1)
.attr("class"));
img.onload = function () {
if (this.complete) {
console.log(
progressData.data("name")
+ " preview loading..."
);
};
};
uploads.append("<br /><li>", img, "</li><br />");
};
}
return xhrUpload;
}
})
.then(function (data, textStatus, jqxhr) {
console.log(data)
this.find("img[class=" + jqxhr.name + "]")
.attr("src", data.file)
.before("<span>" + data.name + "</span><br />");
return data
}, function (jqxhr, textStatus, errorThrown) {
console.log(errorThrown);
return errorThrown
});
})
});
$.when.apply(display, images).then(function () {
var result = $.makeArray(arguments);
console.log(result.length, "uploads complete");
}, function err(jqxhr, textStatus, errorThrown) {
console.log(jqxhr, textStatus, errorThrown)
})
};
$(document)
.on("change", "input[name^=file]", processFiles);
// process `droppable` events
droppable.ondragover = function () {
$(this).addClass("hover");
return false;
};
droppable.ondragend = function () {
$(this).removeClass("hover")
return false;
};
droppable.ondrop = function (e) {
$(this).removeClass("hover");
var image = Array.prototype.slice.call(e.dataTransfer.files)
.every(function (img, i) {
return /^image/.test(img.type)
});
e.preventDefault();
// if `file`, file type `image` , process `file`
if (!!e.dataTransfer.files.length && image) {
$(this).find(".drop-area-label")
.css("color", "blue")
.html(function (i, html) {
$(this).delay(3000, "msg").queue("msg", function () {
$(this).css("color", "initial").html(html)
}).dequeue("msg");
return "File dropped, processing file upload...";
});
processFiles(e);
} else {
// if dropped `file` _not_ `image`
$(this)
.removeClass("hover")
.addClass("err")
.find(".drop-area-label")
.css("color", "darkred")
.html(function (i, html) {
$(this).delay(3000, "msg").queue("msg", function () {
$(this).css("color", "initial").html(html)
.parent("#drop").removeClass("err")
}).dequeue("msg");
return "Please drop image file...";
});
};
};
php
<?php
if (isset($_POST["file"])) {
// do php stuff
// call `json_encode` on `file` object
$file = json_encode($_POST["file"]);
// return `file` as `json` string
echo $file;
};
jsfiddle http://jsfiddle.net/guest271314/0hm09yqo/

How to remove header in PDF export result from DataTable and change color table fill to white?

I tried removing the header in the exported PDF from the DataTable but it didn't work. Also, how to change the color table to full white and border black?
var table = $('#ReportTable').DataTable( {
lengthChange: false,
buttons: [
{"extend": 'pdf',
"className": 'btn btn-sm btn-primary rounded-pill px-3 mb-3 mb-sm-0',
customize: function(doc) {
doc.header = false;
doc.pageMargins = [ 150, 20, 150, 20 ];
},
},
{
"extend": 'print',
"className": 'btn btn-sm btn-primary rounded-pill px-3 mb-3 mb-sm-0'
},
]
} );
table.buttons().container()
.appendTo( '#ReportTable_wrapper .col-md-6:eq(0)' );
You can use title to control the title ("SiPanda") and you can use customize to control the different colors (striped lines) used for alternate rows in the PDF.
I don't want to interfere with your existing use of customize, so here is my test example which you can use as a model:
var table = $('#example').DataTable( {
dom: 'Brftip',
buttons: [
{
extend: 'pdfHtml5',
text: 'To PDF',
title: '',
customize: function ( pdf, btn, tbl ) {
delete pdf.styles.tableBodyOdd.fillColor;
}
}
]
} );
The title: '' is straightforward (assuming your PDF is actually getting its title from the web page's title).
The delete pdf.styles.tableBodyOdd.fillColor; assumes that your DataTable is using the "standard" zebra-stripes" style.
This command works because the DataTable passes the following properties to PDFMake:
tableBodyEven: Object { }
tableBodyOdd: Object { fillColor: "#f3f3f3" }
So, we remove the fillColor: "#f3f3f3" property from the tableBodyOdd object.
If you have used a different DataTables styling, you may see something different from what I see - in which case you can use console.log( pdf ); to take a closer look.
UPDATE
I missed the part about "and border black" - so here is an approach for that, also:
buttons: [
{
extend: 'pdfHtml5',
text: 'To PDF',
title: '',
customize: function ( pdf, btn, tbl ) {
delete pdf.styles.tableBodyOdd.fillColor;
pdfMake.tableLayouts = {
exampleLayout: {
hLineWidth: function (i) {
return 0.2;
},
vLineWidth: function (i) {
return 0.2;
},
hLineColor: function (i) {
return 'black';
},
vLineColor: function (i) {
return 'black';
}
//paddingLeft: function (i) {
// return i === 0 ? 0 : 8;
//},
//paddingRight: function (i, node) {
// return (i === node.table.widths.length - 1) ? 0 : 8;
//}
}
};
pdf.content[0].layout = "exampleLayout";
}
}
]
In the above snippet, I define an object called pdfMake.tableLayouts which contains a custom object called exampleLayout.
My exampleLayout defines thin black lines around every cell in the table.
I then use this custom layout by using:
pdf.content[0].layout = "exampleLayout";
You can choose your own line widths and colors.
The end result:

Jquery dialog confimation before ajax post to a controller + asp .net mvc3 + c#

I have a toggle button which works perfectly. The javascript and view is below:
jQuery:
$('.list-delist-link').delegate("a", "click", function (e) {
var obj = $(this);
if ($(this).hasClass('delist-property')) {
// Post to controller
e.preventDefault();
} else {
// Post to controller
e.preventDefault();
}
});
View:
<div class="list-delist-link">
#if(item.IsPropertyDisabled) {
#Html.ActionLink("List", "Enable", "Property", new { id = item.PropertyId }, new { #class="list-property other-button" })
} else {
#Html.ActionLink("Delist", "Disable", "Property", new { id = item.PropertyId }, new { #class="delist-property other-button" })
}
</div>
However, now I want to add a confirmation dialog box before the ajax action. However, everything breaks up when I am try to do that ... I am not sure why. I have the jQuery and css files on the layout page
The changes I made are listed below:
Changes to jQUery:
var obj;
$('.list-delist-link').delegate("a", "click", function (e) {
obj = $(this);
$("#dialog-confirm").dialog(open):
e.preventDefault();
});
Additional jQuery for modal confirmation:
$(function() {
$( "#dialog-confirm" ).dialog({
resizable: false, height:140, modal: true,
buttons: {
"Delete all items": function() {
if (obj.hasClass('delist-property')) {
// Post to controller
} else {
// Post to controller
}
$(this).dialog("close");
},
Cancel: function() {
$(this).dialog("close");
}
}
});
});
Additional div in View:
<div id="dialog-confirm" title="Are you sure?">
<p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>
Can you please tell me what is wrong?
You must add autoOpen: false, look this
$( "#dialog-confirm" ).dialog({
autoOpen : false,
resizable: false, height:140, modal: true,
buttons: {......

jquery tooltip on dynamic element

I use this tooltip plugin to make the tooltip on element as
$('.showtooltip').tooltip({
delay: 0,
track: true,
showURL: false,
bodyHandler: function() {
var tipStr = "SOME DISPLAY HTML";
return $(tipStr);
}
});
And my ajax create element dynamically.
$("<img alt='' class='showtooltip' src='image.jpg' />");
so when this image is added to document. The tooltip doesn't display.
Then I use live() in jquery :
$(".showtooltip").live("mouseover", function() {
$(this).tooltip({
delay: 0,
track: true,
showURL: false,
bodyHandler: function() {
var tipStr = "SOME DISPLAY HTML";
return $(tipStr);
}
})
});
But tooltip only display after the first time mouse over the image.
How can i use tooltip on dynamic element ?
I used something like this to rebind after an ajax call. It may help.
$(".showtooltip").live("mouseover",function(){
if (!$(this).hasClass("tooledUp")){
$(this).tooltip({
delay: 0,
track: true,
showURL: false,
bodyHandler: function() {
var tipStr = "SOME DISPLAY HTML";
return $(tipStr);
}
});
$(this).tooltip().show();
$(this).addClass("tooledUp");
}
});
From the forum here: http://static.flowplayer.org/tools/forum/30/37281
<input type="button" id="btn" value ="Click here" />
$(document).ready(function(){
$("#btn").click(function(){
$("<input type='checkbox' title='waaaaw' />").appendTo($(this).parent()).ready(function(){
$(this).tooltip({
delay: 0,
track: true,
showURL: false,
bodyHandler: function() {
var tipStr = "SOME DISPLAY HTML";
return $(tipStr);
}
}).addClass("tooledUp").show();
});
});
});

Resources