get size of file jquery - javascript

My view I want to check file if it bigger than 500 kb give for example alert()
<img src="#Model.Value" width="95" height="80" id="down-load" data-id="#Model.Key" data upload="#Url.Action("AddPreview", "Images")" />
(function ($) {
$("[data-id]").each(function () {
var $this = $(this);
$($this).upload({
name: 'attachments',
action: $this.data("upload"),
enctype: 'multipart/form-data',
params: {},
autoSubmit: true,
onSubmit: function () { },
onSelect: function () {
var size = $('#down-load')[0].files[0].size;//do not work
},
onComplete: function (e) {
if (e.charAt(0) != '[') {
$.fn.showUserActionNotification(e, true);
return;
}
var data = JSON.parse(e);
if (data[0].Error) {
$.fn.showUserActionNotification(data[0].Error, true);
}
else if (data[0].Preview) {
$this.attr("src", data[0].Preview);
}
}
});
$this.parent().find("input").css("cursor", "pointer");
});
})(jQuery);
I want to get size on function onSelect to check it on big
Is any body can help me?

I have done function
var imageSize = function (e) {
return $.map(e.files, function (file) {
var name = file.name;
var size = file.size;
if (size > 512000) {
var alert = $(".valid-size-goods").text(name + ": " + (size / 1024).toFixed(2) + " kb");
alert.dialog({
title: alert.attr("dlgTitle"),
modal: true,
resizable: false,
buttons: [{ text: alert.attr("btn"), click: function () { $(this).dialog("close"); } }]
}); return false;
}
return true;
});
};
and put it to onSelect:imageSize(e)

Related

Angular js fileupload allow only image extensions

Here is my directive for uploading image profile. It is working fine but what I wanted to know is that how can we filter on this directive to allow only particular extensions, cause I wanted to allow only images. I am using fineupload by the way. Feel free to ask about the code below the image url is e.target.result.
app.directive('uploadProfile', function () {
return function (scope, element, attrs, $window) {
var $uploadCrop;
function readFile(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.cropper').addClass('ready')
$window.alert("hi")
$uploadCrop.croppie('bind', {
url: e.target.result
}).then(function () {
console.log("do nothing")
});
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
$(element).on("change", function () {
readFile(this)
});
$uploadCrop = $('.cropper').croppie({
url: "/static/img/yahshua.jpg",
viewport: {
width: 170,
height: 170,
type: 'circle',
},
enableExif: true,
enableZoom: true,
enforceBoundary: false
});
$(element).on('change', function () { readFile(this); });
$('#cropImage').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'base64',
size: 'viewport'
}).then(function (resp) {
scope.record = {}
scope.record.cropped = resp
scope.main.upload_profile(resp)
});
});
};
})
I your html input of type 'file' you can add 'accept' attribute to limit file type to images only :
https://developer.mozilla.org/fr/docs/Web/HTML/Element/Input/file
<input type="file"
id="avatar" name="avatar"
accept="image/png, image/jpeg">
Reviewed all of your code and commented
solution is to use just set the file input attribute to accept="image/*"
app.directive('uploadProfile', function () {
return function (scope, element, attrs, $window) {
var $uploadCrop;
function readFile(input) {
// if (input.files && input.files[0]) {
// files are always avalible nowdays
if (input.files[0]) {
// You don't need the FileReader... (we will use object urls)
// var reader = new FileReader();
// reader.onload = function (e) {
$('.cropper').addClass('ready')
$window.alert('hi')
$uploadCrop.croppie('bind', {
url: URL.createObjectURL(input.files[0])
}).then(function () {
console.log("do nothing")
});
// }
// reader.readAsDataURL(input.files[0]);
}
// All browswers support FileReader nowdays...
// else {
// swal("Sorry - you're browser doesn't support the FileReader API");
// }
}
// set file attribute's accept to "image/*"
// This will only allow users to only select images
element.accept = 'image/*'
$(element).on("change", function () {
readFile(this)
});
$uploadCrop = $('.cropper').croppie({
url: "/static/img/yahshua.jpg",
viewport: {
width: 170,
height: 170,
type: 'circle',
},
enableExif: true,
enableZoom: true,
enforceBoundary: false
});
// You are already doing this above
// $(element).on('change', function () { readFile(this); });
$('#cropImage').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'base64', // I would encurage you to use blob & FormData instead
size: 'viewport'
}).then(function (resp) {
scope.record = {}
scope.record.cropped = resp
scope.main.upload_profile(resp)
});
});
};
})

Handsontable autosave - ajax not defined

I copied the code from Handsontable official documentation, into a JSFiddle. This is handsontable 0.34.5.
I am getting an error in chrome console:
"ajax is not defined".
Code as follows, pre-loaded with handsontable.full.min.js and handsontable.full.min.css
HTML:
<div class="ajax-container">
<div class="controls">
<button name="load" id="load" class="intext-btn">Load</button>
<button name="save" id="save" class="intext-btn">Save</button>
<label>
<input type="checkbox" name="autosave" id="autosave" checked="checked" autocomplete="off">Autosave</label>
</div>
<pre id="example1console" class="console">Click "Load" to load data from server</pre>
<div id="example1" class="hot handsontable"></div>
</div>
Script:
var
$$ = function(id) {
return document.getElementById(id);
},
container = $$('example1'),
exampleConsole = $$('example1console'),
autosave = $$('autosave'),
load = $$('load'),
save = $$('save'),
autosaveNotification,
hot;
hot = new Handsontable(container, {
startRows: 8,
startCols: 6,
rowHeaders: true,
colHeaders: true,
afterChange: function(change, source) {
if (source === 'loadData') {
return; //don't save this change
}
if (!autosave.checked) {
return;
}
clearTimeout(autosaveNotification);
ajax('scripts/json/save.json', 'GET', JSON.stringify({
data: change
}), function(data) {
exampleConsole.innerText = 'Autosaved (' + change.length + ' ' + 'cell' + (change.length > 1 ? 's' : '') + ')';
autosaveNotification = setTimeout(function() {
exampleConsole.innerText = 'Changes will be autosaved';
}, 1000);
});
}
});
Handsontable.dom.addEvent(load, 'click', function() {
ajax('scripts/json/load.json', 'GET', '', function(res) {
var data = JSON.parse(res.response);
hot.loadData(data.data);
exampleConsole.innerText = 'Data loaded';
});
});
Handsontable.dom.addEvent(save, 'click', function() {
// save all cell's data
ajax('scripts/json/save.json', 'GET', JSON.stringify({
data: hot.getData()
}), function(res) {
var response = JSON.parse(res.response);
if (response.result === 'ok') {
exampleConsole.innerText = 'Data saved';
} else {
exampleConsole.innerText = 'Save error';
}
});
});
Handsontable.dom.addEvent(autosave, 'click', function() {
if (autosave.checked) {
exampleConsole.innerText = 'Changes will be autosaved';
} else {
exampleConsole.innerText = 'Changes will not be autosaved';
}
});
The code of the ajax function they are using is rather simple, is just a wrapper around XMLHttpRequest.
NOTE: I got it by just executing ajax.toString() via devtools on their docs page. It isn't referencing external functions, so it will work as is.
function ajax(url, method, params, callback) {
var obj;
try {
obj = new XMLHttpRequest();
} catch (e) {
try {
obj = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
obj = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support Ajax.");
return false;
}
}
}
obj.onreadystatechange = function () {
if (obj.readyState == 4) {
callback(obj);
}
};
obj.open(method, url, true);
obj.setRequestHeader("X-Requested-With", "XMLHttpRequest");
obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
obj.send(params);
return obj;
}

How can I implement a wait mechanism until receiving confirm dialog response?

Here is my code:
$(function () {
$(document).on('click', '.fa-times', function(e){
e.stopPropagation();
var result = ConfirmDialog('Are you sure?');
if (result) {return false}
var row = $(this).closest('tr');
row.css('opacity','0.3');
var word = $(this).closest('td').siblings('.word').text();
$.ajax({
url : '../../te_addStopWord',
type : 'GET',
data: {word : word},
dataType : 'JSON',
success : function () {
row.remove();
}, // success
error : function ($a,$b,$c) {
alert($b);
row.css('opacity','1');
}
}); // ajax
})
function ConfirmDialog(message) {
$('<div></div>').appendTo('body')
.html('<div><h6>'+message+'?</h6></div>')
.dialog({
modal: true, title: 'Delete message', zIndex: 10000, autoOpen: true,
width: 'auto', resizable: false,
buttons: {
Yes: function () {
$(this).remove();
return true;
},
No: function () {
$(this).remove();
return false;
}
},
close: function (event, ui) {
$(this).remove();
}
});
};
})
But my code run that ajax request without waiting for the response of ConfirmDialog(message) function. How can I force it to wait?
You have 2 functions which get triggered depending on which confirm button is selected. Handle your ajax code from there.
I liked how Abhijit's answer abstracted out the code, but I think he missed something.
$(function() {
$(document).on('click', '.fa-times', function(e) {
e.stopPropagation();
function getConfirmHandler(element){
return function handleConfirm(result) {
if (result) {
return false
}
var row = element.closest('tr');
row.css('opacity', '0.3');
var word = element.closest('td').siblings('.word').text();
$.ajax({
url: '../../te_addStopWord',
type: 'GET',
data: {
word: word
},
dataType: 'JSON',
success: function() {
row.remove();
}, // success
error: function($a, $b, $c) {
alert($b);
row.css('opacity', '1');
}
}); // ajax
}
}
ConfirmDialog('Are you sure?', getConfirmHandler($(this)))
});
function ConfirmDialog(message, callback) {
$('<div></div>').appendTo('body')
.html('<div><h6>' + message + '?</h6></div>')
.dialog({
modal: true,
title: 'Delete message',
zIndex: 10000,
autoOpen: true,
width: 'auto',
resizable: false,
buttons: {
Yes: function() {
$(this).remove();
callback(true);
},
No: function() {
$(this).remove();
callback(false);
}
},
close: function(event, ui) {
$(this).remove();
}
});
};
})
Try move ajax into your ConfirmDialog:yesfunction. Or Try to use promise.
buttons: {
Yes: function () {
var row = $(this).closest('tr');
row.css('opacity','0.3');
var word = $(this).closest('td').siblings('.word').text();
$.ajax({
url : '../../te_addStopWord',
type : 'GET',
data: {word : word},
dataType : 'JSON',
success : function () {
row.remove();
}, // success
error : function ($a,$b,$c) {
alert($b);
row.css('opacity','1');
}
}); // ajax
$(this).remove();
return true;
},
No: function () {
$(this).remove();
return false;
}
},

scope of javascript variable in the class

inside click_save() method of Controller, this is not pointing to the controller instance, but instead it points to button instance
How to get access to this. so it points to controller and I can do this.userModelDialog().method call
```
// --- Controller manages/dispatches tasks of view and model
function Controller() {
var controller = this;
api = new API();
var table = $('#table');
this.userModelDialog = new UserModalDialog();
$('button[data-type="edituser"]').on("click", function(e) {
controller.click_button(this);
});
// Register the button handlers
$.each(["save", "close", "copy", "delete", "reset"], function(index, id) {
msg.clear();
$("#" + id).click(controller["click_" + id]);
});
}
$.extend(Controller.prototype, {
click_user: function(id) {
api.getUser(id)
.done(function(data) {
_.keys(data).forEach(function(property) {
$('#' + property).val(data[property]);
});
})
.fail(function(data) {
alert('fail');
});
$('#userDetails').modal('show');
},
click_button: function(button) {
var id = $(button).attr('data-id');
this.click_user(id);
},
click_save: function(button) {
this.userModelDialog.submit();
msg.show({
TYPE: 'success',
MESSAGE: 'saved successfull!'
});
$('#userDetails').modal('hide');
},
click_new: function() {
},
click_copy: function() {
},
click_delete: function() {
},
click_reset: function() {
},
click_row: function(row) {
var id = $(row).attr('data-uniqueid');
this.click_user(id);
},
updateFromServer: function(data, callback) {
msg.show(data);
callback(data);
}
});
```
// Register the button handlers
$.each(["save", "close", "copy", "delete", "reset"], function(index, id) {
msg.clear();
var methodName = 'click_' + id;
if (controller[methodName]) {
$("#" + id).click(controller[methodName].bind(controller));
} else {
console.log('There is not method in class with name: ' + methodName);
}
});

Trigger a java script in before submit form

Hello while creating my php script I came across a difficulty to execute script 1[ajax uploader] ( on from submit ). The code that triggers the upload is uploadObj.startUpload(); i tried to add it on script 2 in before submit action, but somehow it doesn't lunch. Can you help me?
Script 1.
var uploadObj = $("#mulitplefileuploader").uploadFile({
url: "uploader/upload.php",
multiple: false,
fileName: "myfile",
maxFileSize: 655360 * 100, //5mb
allowedTypes: "jpg,png,gif,zip,txt,doc,docx,csv,xml,pdf,JPG,JPEG,jpeg",
maxFileCount: 1,
autoSubmit: false,
dragDropStr: "<span><b>Przeciągnij i upuść plik</b></span>",
abortStr: "Anuluj",
cancelStr: "Przerwij",
doneStr: "Dodano",
dynamicFormData: function () {
var data = {
uid: "<?PHP echo $_SESSION['userid']; ?>"
}
return data;
},
onSubmit: function (files) {
$("#eventsmessage").html($("#eventsmessage").html() + "<br/>Submitting:" + JSON.stringify(files));
},
onSuccess: function (files, data, xhr) {
$("#eventsmessage").html($("#eventsmessage").html() + "<br/>Success for: " + JSON.stringify(data));
},
afterUploadAll: function () {
$("#eventsmessage").html($("#eventsmessage").html() + "<br/>All files are uploaded");
},
onError: function (files, status, errMsg) {
$("#eventsmessage").html($("#eventsmessage").html() + "<br/>Error for: " + JSON.stringify(files));
}
});
Script 2.
$(document).ready(function () {
var options = {
target: "#msgholder",
beforeSubmit: function () {
showLoader;
},
success: showResponse,
url: "ajax/controller.php",
resetForm: 0,
clearForm: 0,
data: {
processTicket: 1
}
};
$("#admin_form").ajaxForm(options);
});
function showResponse(msg) {
hideLoader();
$(this).html(msg);
$("html, body").animate({
scrollTop: 0
}, 600);
}

Categories

Resources