Get Count of selected files in Telerik Upload - telerik-mvc

I need to get a count of all selected files using Telerik MVC Upload Control. Can anyone tell me how can i do that. I tried code like this.
var count = e.files.length;
But its counting always as one.

try this code
[function onSelect(e) {
var selectedFiles = e.files.length;
totalFiles += selectedFiles;
}
function UploadRemove(e) {
totalFiles--;
if (totalFiles > 0) {
// Write true block code here.
}
else if (totalFiles == 0) {
// Write your false block code here.
}
}]

You could do this in your upload event handler:
upload: function (e) {
// File Count:
var fileCount = this.wrapper.find(".k-file").length;
// File Index:
var uid = e.files[0].uid;
var file = this.wrapper.find(".k-file[data-uid='" + uid + "']");
var fileIndex = file.index();
}

Related

npm exceljs is unable to read any existing file

// read from a file
const workbook = new Excel.Workbook();
await workbook.xlsx.readFile(filename);
// ... use workbook
As per the exceljs documentation, it should load the already existing file 'filename', but when I tried reading it,
const sheet = workbook.addWorksheet('My Sheet');
sheet was actually undefined.
My concern is, is it possible to do read from and write to a file operations in ReactJS, also I came across another article
https://stackoverflow.com/questions/49491710/can-reactjs-write-into-file#:~:text=React%20runs%20in%20browser%20so,gets%20served%20to%20the%20browser
that suggest it is not possible
My project did read and write on the same file template using exceljs in node js. Hope can help you.
workbook.xlsx.readFile(template)
.then(function () {
// machines
var wsMachine = workbook.getWorksheet('No');
wsTemplate = _.cloneDeep(wsMachine);
for (var index = 1; index <= 10; index++) {
var copySheet = workbook.addWorksheet('No' + index, { state: 'visible' });
copySheet.pageSetup.printArea = 'A1:FE219';
var ws = _.cloneDeep(wsTemplate);
copySheet.model = Object.assign(ws.model, {
mergeCells: ws.model.merges
});
copySheet.name = 'No' + index;
}
wsMachine.state = 'hidden';
wsTemplate.state = 'hidden';
return workbook.xlsx.writeFile(urlOutput);
})
.then(function () {
return true
})
.catch(function () {
return false;
});
Happy code

ReactJS file upload Axios

I am having form with 4 file upload fields, that users can submit up to 4 images.
I am adding files to array, loop and upload to server with PHP.
Now everything seams to be working fine.. but returned image names (I am using those to store in DB) are not in the same order as I am uploading them:
Here is example of code:
if (postImage1 !== null) {
postImagesArray.push(postImage1);
}
if (postImage2 !== null) {
postImagesArray.push(postImage2);
}
if (postImage3 !== null) {
postImagesArray.push(postImage3);
}
if (postImage4 !== null) {
postImagesArray.push(postImage4);
}
//Loop Array and make upload......
var startCount = 1;
var endCount = postImagesArray.length;
for (var i = 0; i < postImagesArray.length; i++) {
var currentImage = postImagesArray[i];
//##### UPLOADING IMAGE ###########
try {
var base_url = 'https://##############.com/uploadImage.php';
var fd = new FormData();
fd.append('avatar', currentImage, 'post.jpg');
axios.post(base_url, fd).then((res) => {
console.log(res);
if (res.data.status === 'success') {
let fileConstruct =
'https://############.com/' +
res.data.fileName +
'?fit=crop&w=840&q=80';
uploadImagesArray.push(fileConstruct);
} else {
// there was an error with file upload... revert to default...
console.log('No error but no image either......');
}
if (startCount == endCount) {
uploadImagesConstruct();
}
startCount++;
});
} catch (err) {
//console.error(err);
console.log(
'There was an error uploading file to the web server: ' + err
);
if (startCount == endCount) {
uploadImagesConstruct();
}
}
Interesting thing is, images are mixed up always in the same order... (so it is not random), instead of returned image1,image2,image3,image4 I am getting image3, image2, image4, image1....If I post only 2 images it is image2,image1.... so first image is always returned last.....
Can anybody see what I am doing wrong..
Thanks!!!!
If anyone need this in the future....
I simply added underscore and postion in the loop "_i" before ".jpg" when I am constructing file names..
fd.append('avatar', currentImage, 'post.jpg');
now is:
fd.append('avatar', currentImage, `post_${i}.jpg`);
and since I am putting all records in the array
uploadImagesArray.push(fileConstruct);
I just resorted it.. by the numbers I added..
uploadImagesArray.sort(function(x, y) {
var xp = x.substring(x.lastIndexOf('_') + 1, x.lastIndexOf('.jpg'));
var yp = y.substring(y.lastIndexOf('_') + 1, y.lastIndexOf('.jpg'));
return xp == yp ? 0 : xp < yp ? -1 : 1;
});

How to apply delay in JSZip API to load?

How to apply delay in JSZip API ? I want to zip multiple file. but I want to add some delay between transferring the files from webserver. How to add delay in below code?
This is for browser and deploying binaries inside the device.
$scope.download = function () {
var urls = ["/FILES/AlertLog.txt",
"/FILES/AuditLog.txt",
"/FILES/TotLog.txt",
"/FILES/Historian.csv",
"/FILES/History2.csv",
"/FILES/Factory.cfg",
"/FILES/SLog.txt",
"/FILES/se.dump",
"/FILES/AssertLog.txt",
"/FILES/History2.csv",
"/FILES/History3.csv",
"/FILES/History4.csv"
];
compress_files(urls);
}
function compress_files(urls) {
var zip = new JSZip();
var deferreds = [];
for (var i = 0; i < urls.length; i++) {
$timeout(function(){ deferreds.push(addToZip(zip, urls[i], i));
},200);// issue to deferreds variable =>undefined
$.when.apply(window, deferreds).done(generateZip);
}
function addToZip(zip, url, i) {
var deferred = $.Deferred();
JSZipUtils.getBinaryContent(url, function (err, data) {
if(err) {
deferred.resolve(zip);
}
else {
var arr=url.split("/");
zip.file(arr[2], data, { binary: true });
deferred.resolve(zip);
}
});
return deferred;
}
add some delay of milliseconds between transferring the files from the webserver.
I am trying to download the individual file by giving some delay. It fixed my problem
function downloadAll(files){
if(files.length == 0) return;
file = files.pop();
var theAnchor = $('<a />')
.attr('href', file[1])
.attr('download',file[0])
// Firefox does not fires click if the link is outside
// the DOM
.appendTo('body');
theAnchor[0].click();
theAnchor.remove();
downloadAll(files); }
function downloadAll(files){
if(files.length == 0) return;
file = files.pop();
var theAnchor = $('<a />')
.attr('href', file[1])
.attr('download',file[0])
// Firefox does not fires click if the link is outside
// the DOM
.appendTo('body');
theAnchor[0].click();
theAnchor.remove();
downloadAll(files);
}
$('a.download-csv').on('click', function(){
downloadAll([
['file1.csv', 'data:text/csv;charset=utf8,'+
encodeURIComponent('my,csv,file\and,so,on')],
['file2.txt', 'data:text/plain;charset=utf8,'+
encodeURIComponent('this script can do what I need.')],
['file3.js', 'data:text/javascriptcharset=utf8,'+
encodeURIComponent('alert(\'You can donate me your house if you like this script :-) \')')]
]);
});

Save UIImage as jpg File in Photo Library Directory in Xamarin.iOS

As I know this is Simple Approch to save it in a Photo Library. But It can save with custom filename.
var someImage = UIImage.FromFile("someImage.jpg");
someImage.SaveToPhotosAlbum((image, error) => {
var o = image as UIImage;
Console.WriteLine("error:" + error);
})
But I want to save it with filename.jpg in the Photo Library.
I try so much code but nothing is getting help to me.
Code 1 :
var imageName = "/" + dicomId.ToString() + ".jpg";
var documentsDirectory = Environment.GetFolderPath
(Environment.SpecialFolder.Personal);
string jpgFilename = System.IO.Path.Combine(documentsDirectory, imageName); // hardcoded filename, overwritten each time
NSData imgData = dicomImage.AsJPEG();
NSError err = null;
if (imgData.Save(jpgFilename, false, out err))
{
Console.WriteLine("saved as " + jpgFilename);
}
else
{
Console.WriteLine("NOT saved as " + jpgFilename + " because" + err.LocalizedDescription);
}
This code part goes to if condition but it can not save the Image.
Code 2 :
If using this part of Code
var documentsDirectoryPath = NSSearchPath.GetDirectories(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User, true)[0];
It give you don't have permission to save image.
I try lots of thing on google and SO but nothing could help to me.
Edit :
info.plist
Any Help would be Appreciated.
How about using UIImage.SaveToPhotosAlbum()?
Usage is something like:
image.SaveToPhotosAlbum((uiImage, nsError) =>
{
if (nsError != null)
// do something about the error..
else
// image should be saved
});
Make sure that you have requested permissions before you try to save.
PHPhotoLibrary.RequestAuthorization(status =>
{
switch (status)
{
case PHAuthorizationStatus.Restricted:
case PHAuthorizationStatus.Denied:
// nope you don't have permission
break;
case PHAuthorizationStatus.Authorized:
// yep it is ok to save
break;
}
});
Edit: if you want more control, you need to use PHPhotosLibrary, which is an awful API...
var library = PHPhotoLibrary.SharedPhotoLibrary;
var albumName = "MyPhotos";
var fetchOptions = new PHFetchOptions();
fetchOptions.Predicate = NSPredicate.FromFormat($"title = {albumName}");
var assetsCollections = PHAssetCollection.FetchAssetCollections(
PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, fetchOptions);
var collection = assetsCollections.firstObject as PHAssetCollection;
library.PerformChanges(() => {
var options = new PHAssetResourceCreationOptions();
options.OriginalFilename = "filename.jpg";
var createRequest = PHAssetCreationRequest.CreationRequestForAsset();
createRequest.AddResource(PHAssetResourceType.FullSizePhoto, image.AsJPEG(1), options);
// if you want to save to specific album... otherwise just remove these three lines
var placeholder = createRequest.PlaceholderForCreatedAsset;
var albumChangeRequest = PHAssetCollectionChangeRequest.ChangeRequest(collection);
albumChangeRequest.AddAssets(new PHObject[] { placeholder });
},
(ok, error) => {
if (error != null)
{
// someone set up us the bomb
}
});

How to limit the number of dropzone.js files uploaded?

Depending on the use case, how do I constrain the number of files that dropzone.js will allow?
For example, I might need to only allow 1, 2, or 4 files uploaded.
It's not uploadMultiple. Unfortunately, uploadMultiple only applies to the number of files handled per request.
I achieved this a slightly different way. I just remove the old dropped file any time a new file is added. It acts as overwriting the file which was the user experience I was going for here.
Dropzone.options.myAwesomeDropzone = {
accept: function(file, done) {
console.log("uploaded");
done();
},
init: function() {
this.on("addedfile", function() {
if (this.files[1]!=null){
this.removeFile(this.files[0]);
}
});
}
};
Nowell pointed it out that this has been addressed as of August 6th, 2013. A working example using this form might be:
<form class="dropzone" id="my-awesome-dropzone"></form>
You could use this JavaScript:
Dropzone.options.myAwesomeDropzone = {
maxFiles: 1,
accept: function(file, done) {
console.log("uploaded");
done();
},
init: function() {
this.on("maxfilesexceeded", function(file){
alert("No more files please!");
});
}
};
The dropzone element even gets a special style, so you can do things like:
<style>
.dz-max-files-reached {background-color: red};
</style>
I thought that the most intuitive single file upload process was to replace the previous file upon a new entry.
$(".drop-image").dropzone({
url: '/cart?upload-engraving=true',
maxFiles: 1,
maxfilesexceeded: function(file) {
this.removeAllFiles();
this.addFile(file);
}
})
maxFiles: 1 does the job but if you also want to remove the additional files you can use this sample code taken from the Wiki page:
How can I limit the number of files?
You're in luck! Starting with 3.7.0 Dropzone supports the maxFiles
option. Simply set it to the desired quantity and you're good to go.
If you don't want the rejected files to be viewed, simply register for
the maxfilesexceeded event, and remove the file immediately:
myDropzone.on("maxfilesexceeded", function(file)
{
this.removeFile(file);
});
Alternative solution that worked really well for me:
init: function() {
this.on("addedfile", function(event) {
while (this.files.length > this.options.maxFiles) {
this.removeFile(this.files[0]);
}
});
}
You can limit the number of files uploaded by changing in dropezone.js
Dropzone.prototype.defaultOptions = {
maxFiles: 10,
}
Set maxFiles Count: maxFiles: 1
In maxfilesexceeded event, clear all files and add a new file:
event: Called for each file that has been rejected because the number
of files exceeds the maxFiles limit.
var myDropzone = new Dropzone("div#yourDropzoneID", { url: "/file/post",
uploadMultiple: false, maxFiles: 1 });
myDropzone.on("maxfilesexceeded", function (file) {
myDropzone.removeAllFiles();
myDropzone.addFile(file);
});
it looks like maxFiles is the parameter you are looking for.
https://github.com/enyo/dropzone/blob/master/src/dropzone.coffee#L667
Why do not you just use CSS to disable the click event. When max files is reached, Dropzone will automatically add a class of dz-max-files-reached.
Use css to disable click on dropzone:
.dz-max-files-reached {
pointer-events: none;
cursor: default;
}
Credit: this answer
The problem with the solutions provided is that you can only upload 1 file ever. In my case I needed to upload only 1 file at a time (on click or on drop).
This was my solution..
Dropzone.options.myDropzone = {
maxFiles: 2,
init: function() {
this.handleFiles = function(files) {
var file, _i, _len, _results;
_results = [];
for (_i = 0, _len = files.length; _i < _len; _i++) {
file = files[_i];
_results.push(this.addFile(file));
// Make sure we don't handle more files than requested
if (this.options.maxFiles != null && this.options.maxFiles > 0 && _i >= (this.options.maxFiles - 1)) {
break;
}
}
return _results;
};
this._addFilesFromItems = function(items) {
var entry, item, _i, _len, _results;
_results = [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
if ((item.webkitGetAsEntry != null) && (entry = item.webkitGetAsEntry())) {
if (entry.isFile) {
_results.push(this.addFile(item.getAsFile()));
} else if (entry.isDirectory) {
_results.push(this._addFilesFromDirectory(entry, entry.name));
} else {
_results.push(void 0);
}
} else if (item.getAsFile != null) {
if ((item.kind == null) || item.kind === "file") {
_results.push(this.addFile(item.getAsFile()));
} else {
_results.push(void 0);
}
} else {
_results.push(void 0);
}
// Make sure we don't handle more files than requested
if (this.options.maxFiles != null && this.options.maxFiles > 0 && _i >= (this.options.maxFiles - 1)) {
break;
}
}
return _results;
};
}
};
Hope this helps ;)
I'd like to point out. maybe this just happens to me, HOWEVER, when I use this.removeAllFiles() in dropzone, it fires the event COMPLETE and this blows, what I did was check if the fileData was empty or not so I could actually submit the form.
You can also add in callbacks - here I'm using Dropzone for Angular
dzCallbacks = {
'addedfile' : function(file){
$scope.btSend = false;
$scope.form.logoFile = file;
},
'success' : function(file, xhr){
$scope.btSend = true;
console.log(file, xhr);
},
'maxfilesexceeded': function(file) {
$timeout(function() {
file._removeLink.click();
}, 2000);
}
}
Dropzone.options.dpzSingleFile = {
paramName: "file", // The name that will be used to transfer the file
maxFiles: 1,
init: function() {
this.on("maxfilesexceeded", function(file) {
this.removeAllFiles();
this.addFile(file);
});
}
};

Resources