Get file size on change.bs.fileinput - jasny-bootstrap

I'm trying to add a validation system to Jasny Bootstrap Fileinput to validate filesize and image format before continue to next step of the form.
I tried Get file size before uploading without success. This check exists in backend, but as the form is "wizard-like", I want to do this in live mode.
Thanks in advance.

This is how I implemented it for Jasny bootstrap input type in whole project commonly.
Hope this will help some one.
$('.fileinput').on("change.bs.fileinput", function (e) {
var file = $(e.delegateTarget, $("form")).find('input[type=file]')[0].files[0];
var fileExtension = file.name.split(".");
fileExtension = fileExtension[fileExtension.length - 1].toLowerCase();
var arrayExtensions = ["jpg", "jpeg", "png"];
if (arrayExtensions.lastIndexOf(fileExtension) == -1) {
alert('Only Images can be uploaded');
}
else {
if (file["size"] >= 4194304 && (fileExtension == "jpg" || fileExtension == "jpeg" || fileExtension == "png")) {
alert('Max 4 MB of file size can be uploaded.');
$(this).fileinput('clear');
}
}
});

Related

RadAsyncUpload file validation fails

I am using RadAsyncControl but my file validation is failing i have tried to track the issue through this example .. so my scenario says
Wrong file size!
However i have set MaxFileSize property to 20971520
and the file being chosen is 1kb .txt file (notepad)
Here's my code
<telerik:RadAsyncUpload ID="rauEvidenceDocuments" runat="server" AllowedFileExtensions=".doc, .docx, .pdf, .txt. .rtf, .pages, .odt, .ppt, .pptx, .png" MultipleFileSelection="Automatic"
OnClientFileSelected="onClientFileSeleted" OnClientFileUploadFailed="OnClientFileUploadFailed" OnClientValidationFailed="validationFailed" RenderMode="Lightweight" MaxFileSize="20971520">
</telerik:RadAsyncUpload>
function validationFailed(radAsyncUpload, args) {
var $row = $(args.get_row());
var erorMessage = getErrorMessage(radAsyncUpload, args);
var span = createError(erorMessage);
$row.addClass("ruError");
$row.append(span);
//alert('validation failed');
}
function getErrorMessage(sender, args) {
var fileExtention = args.get_fileName().substring(args.get_fileName().lastIndexOf('.') + 1, args.get_fileName().length);
if (args.get_fileName().lastIndexOf('.') != -1) {//this checks if the extension is correct
if (sender.get_allowedFileExtensions().indexOf(fileExtention) == -1) {
return ("This file type is not supported.");
}
else {
return ("This file exceeds the maximum allowed size" /*+ sender._maxFileSize()*/);
}
}
else {
return ("not correct extension.");
}
}
function createError(erorMessage) {
var input = '<span class="ruErrorMessage">' + erorMessage + ' </span>';
return input;
}
P.S. It is a multiselect control
Heyy, so i found the issue it was giving me the wrong reason for validation. i had spaces in AllowedFileExtensions that's what was causing validation to fail.
So Cheers after wasting 2 hrs :)

could not complete operation due to error c00ce514

I have this code as an excel downloader. After the excel has been generated.
But I'm having an error. As stated in the question Title.
The error occurs at the line:
var strResponeText = XMLHttpRequestObject.responseText;
var strUrl = "POSSellThroughReportExcelOpener.aspx?getstatus=1&DateFrom=" + hdnDateFrom.value + "&DateTo=" + hdnDateTo.value + "&customer_id=" + hdnCustomerID.value + "&intdisplayby=" + hdnDisplayBy.value + "&monthorweek=" + hdnMonthOrWeek.value;
if (XMLHttpRequestObject) {
XMLHttpRequestObject.open("POST", strUrl);
XMLHttpRequestObject.onreadystatechange = function () {
if ((XMLHttpRequestObject.readyState == 4) && (XMLHttpRequestObject.status == 200)) {
var hdnRedirectUrl = document.getElementById("hdnRedirectUrl");
var strResponeText = XMLHttpRequestObject.responseText;
var intResponse = new Number(strResponeText);
var spanCallBackStatus = document.getElementById("spanCallBackStatus");
var trClose = document.getElementById("trClose");
if (!isNaN(intResponse)) {
if (intResponse == 1) {
spanCallBackStatus.innerHTML = "Excel Report has been generated."
trClose.style.display = "";
Init();
window.location.href = hdnRedirectUrl.value;
}
else {
GetStatus();
}
}
else {
spanCallBackStatus.innerHTML = strResponeText;
}
}
}
XMLHttpRequestObject.send(null);
}
Any help is greatly appreciated.
Many thanks.
UPDATE - FEB 20,2014 3:55PM (PHILIPPINE TIME)
Hi Guys,
I have found the cause of the error, it is because the content-type is called two times. During Page_Load event and at last line of the Generate Excel function which is not supposed to be. That is why the current content-type after the page loads has been replaced after the generate excel function. Hehe my bad I guess.
Anyway thanks for all the help, advice and useful links.
Good day to all. :D
Internet Explorer can't handle binary responses to AJAX requests like XMLHttpRequestObject, as discussed in this question. You need to handle the response in some other way, depending on what you need to do with it.

InDesign CS5 Script: How do I use BridgeTalk to save new images from Photoshop?

This script is attempting to:
create a new folder
scan an InDesign document for all images
convert all images to grayscale in Photoshop
save new grayscale images in the new folder from Photoshop
Converting the images to grayscale in Photoshop requires the use of the BridgeTalk object, which allows for the communication between InDesign and Photoshop (the usage of the BridgeTalk object seems to be a form of Ajax).
What I have so far is almost working, being that a new folder is created, and InDesign does seem to be communicating with Photoshop via BridgeTalk. But when Photoshop is opened, nothing happens -- no new images are saved, and I'm not sure if the grayscale conversion is taking place or not...
Here is my code:
#target "InDesign"
var inDesignDocument = app.activeDocument;
var newFolder = createFolder(inDesignDocument); // if subdirectory images DNE, create this folder with the function below
sendImagesToPhotoshop(inDesignDocument, newFolder);
//---------------------------------------------------------------------------------------------------------------
function createFolder(doc)
{
try
{
/*
* type-casting the filePath property (of type object) into a String type;
* must be a String type to concatenate with the subdirectory variable (also of type String)
*/
var docPath = String(doc.filePath);
var subdirectory = "/BLACK AND WHITE IMAGES";
}
catch(e)
{
alert(e.message);
exit();
}
var imagesFolder = docPath + subdirectory; // concatenating the two variables
if(!Folder(imagesFolder).exists)
{
Folder(imagesFolder).create();
}
return imagesFolder; // for instantiation outside of this function
} // end of function createFolder
//---------------------------------------------------------------------------------------------------------------
function sendImagesToPhotoshop(doc, folder)
{
var imgs = doc.allGraphics;
var fileName = "";
var img = "";
var imgType = "";
for(var i = 0; i < imgs.length; i++)
{
if(imgs[i].itemLink != null)
{
fileName = imgs[i].itemLink.name;
img = new File(folder + "/" + fileName); // each image instantiated here
imgType = imgs[i].imageTypeName; // image type is determined here (.tif, .jpg, .png, etc..)
alert("The file \"" + fileName + "\"\n\tis a " + imgType + " file.");
// each image exported to the new folder here, by file type
switch(imgType)
{
case "GIF":
alert("This script cannot convert and export the GIF file:\n\t" + fileName + " !");
break;
case "JPG":
case "EPS":
case "PNG":
case "TIFF":
createBridgeTalkMessage(folder);
break;
default:
alert("\tUnlisted image type: " + imgType + "!\nAdd this type to the switch statement.");
break;
} // end of switch statement
} // end of if statement
} // end of for loop
} // end of function sendImagesToPhotoshop
//---------------------------------------------------------------------------------------------------------------
function createBridgeTalkMessage(imagesFolder)
{
var bt = new BridgeTalk();
bt.target = "photoshop";
bt.body = saveNewImageInPhotoshop.toSource() + "(" + imagesFolder.toSource() + ");";
bt.onError = function(e)
{
alert("Error: " + e.body);
}
bt.onResult = function(resObj){};
bt.send();
}// end of function createBridgeTalkMessage
//---------------------------------------------------------------------------------------------------------------
// called from function createBridgeTalkMessage
function saveNewImageInPhotoshop(imagePath)
{
var photoshopDoc = "";
app.displayDialogs = DialogModes.NO; // Photoshop statement, prevents status alerts from interrupting
photoshopDoc.changeMode(ChangeMode.GRAYSCALE); // convert image to GRAYSCALE
photoshopDoc.saveAs(new File(imagePath) );
photoshopDoc.close(SaveOptions.DONOTSAVECHANGES);
} // end of function saveNewImageInPhotoshop
This is based on the work of Kasyan Servetsky, found here: http://forums.adobe.com/message/3817782
Yeah I experienced issues recently with single line comments and indeed using /* ... */ did the trick. I think you can pass a string for your url but need to escape the slashes characters.
It seems you are passing a folder to Photoshop instead of an actual image file. That may probably explain your issue ;)
Loic

How to preview one big picture from local file system using <input>, <img> and canvas

I am try to make an upload picture webpage in mobile phones, but it always run out of memory and the browser quit once the picture is too big.
Here are my code:
<input type="file" id="testFile" />
<img src="" style="position:relative;" id="uploadingImg" />
function setImage() {
var fileList = this.files;
var imageType = /image/;
for(var i = 0;i < fileList.length;i++) {
document.getElementById('uploadingImg').file = fileList[i];
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('uploadingImg').src = e.target.result;
}
reader.readAsDataURL(fileList[i]);
}
}
document.getElementById('testFile').addEventListener('change', setImage, false);
Does anyone knows how to preview one picture by using <img> or <canvas> element?
Please don't use "readAsDataURL", because when it comes to document.getElementById('uploadingImg').src = e.target.result;
It will run out of memory. Because the base64 Url occupy too much memory and it exist in the memory with many three or four copies.
How can I use "readAsArrayBuffer" and use "drawImage" by canvas?
or other method?
All is ok if I can preview one picture in local disk without using "readAsDataUrl".
Thanks!
In most browsers you don't need to use FileReader (and consequently readAsDataUrl) for this. Instead, you can use the File API's createObjectURL method. Here's your setImage() function rewritten:
function setImage() {
var file = this.files[0];
var URL = window.URL || window.webkitURL;
if (URL.createObjectURL && (file.type == "image/jpeg" || file.type == "image/png" || file.type == "image/gif")) {
document.getElementById('uploadingImg').src = URL.createObjectURL(file);
} else {
alert('Unable to show preview');
}
}
Browser support is still a bit patchy, though, so check support tables such as caniuse.com before deciding whether to use it:
http://caniuse.com/#search=createobjectURL

SlickGrid - Editable Grid with Controls Visible by default

The SlickGrid supports editors for a cell that can be configured to be displayed on click or double click. However I don't see an option where, the editor is VISIBLE by default for all cells without having to click/double click on the cell.
Is it possible to support editors in slick grid where the editors are
"init" by default for all cells?
Is there a known workaround?
Thank you.
I know it's not exactly what you asked for, but I thought I'd add the code below in case anyone finds it useful. It's a semi-workaround and it at least lets the user navigate around the grid and start typing in the cell to edit, without having to "initialise" the edit first by pressing Enter or double-clicking the cell; a bit like editing an MS Excel sheet.
myGrid.onKeyDown.subscribe(function (e, args) {
var keyCode = $.ui.keyCode,
col,
activeCell = this.getActiveCell();
/////////////////////////////////////////////////////////////////////
// Allow instant editing like MS Excel (without presisng enter first
// to go into edit mode)
if (activeCell) {
col = activeCell.cell;
// Only for editable fields and not if edit is already in progress
if (this.getColumns()[col].editor && !this.getCellEditor()) {
// Ignore keys that should not activate edit mode
if ($.inArray(e.keyCode, [keyCode.LEFT, keyCode.RIGHT, keyCode.UP,
keyCode.DOWN, keyCode.PAGE_UP, keyCode.PAGE_DOWN,
keyCode.SHIFT, keyCode.CONTROL, keyCode.CAPS_LOCK,
keyCode.HOME, keyCode.END, keyCode.INSERT,
keyCode.TAB, keyCode.ENTER]) === -1) {
this.editActiveCell();
}
}
}
}
No. The grid is designed to have one cell editable at a time.
Below is what I ended up with (improved version njr101's answer) to make this work. I've added a check for CTRL key so it doesn't break the copy paste plugin I use on the grid.
function (e) {
var keyCode = $.ui.keyCode,
col,
activeCell = this.getActiveCell(),
activeCellNode = this.getActiveCellNode();
var isInEditMode = $(activeCellNode).hasClass("editable");
if (activeCell && !isInEditMode) {
col = activeCell.cell;
if (this.getColumns()[col].editor && !e.ctrlKey) {
if ($.inArray(e.keyCode, [keyCode.LEFT, keyCode.RIGHT, keyCode.UP,
keyCode.DOWN, keyCode.PAGE_UP, keyCode.PAGE_DOWN,
keyCode.SHIFT, keyCode.CONTROL, keyCode.CAPS_LOCK,
keyCode.HOME, keyCode.END, keyCode.INSERT,
keyCode.TAB, keyCode.ENTER]) === -1) {
this.editActiveCell();
}
}
}
};
and dont forget to subscribe:
slickGrid.onKeyDown.subscribe();
Update to use editor define in row metadata and not in column definition.
In my case, one row of two contains in cell 1 text editor and one row of two contains nothing.
grid.onKeyDown.subscribe( function ( e, args ) {
var keyCode = $.ui.keyCode;
var activeCell = this.getActiveCell();
if( activeCell ) {
// get metadata
var columnDefinition = grid.getColumns()[ activeCell.cell ];
var rowMetadata = dataView.getItemMetadata && dataView.getItemMetadata( activeCell.row );
var rowColMetadata = rowMetadata && rowMetadata.columns;
rowColMetadata = rowColMetadata && ( rowColMetadata[ columnDefinition.id ] || rowColMetadata[ activeCell.cell ] );
if ( rowColMetadata && rowColMetadata.editor && !this.getCellEditor() ) {
if( $.inArray( e.keyCode, [keyCode.LEFT, keyCode.RIGHT, keyCode.UP, keyCode.DOWN, keyCode.PAGE_UP, keyCode.PAGE_DOWN,
keyCode.SHIFT, keyCode.CONTROL, keyCode.CAPS_LOCK, keyCode.HOME, keyCode.END, keyCode.INSERT,
keyCode.TAB, keyCode.ENTER]) === -1 ) {
this.editActiveCell();
}
}
}
});

Resources