JQuery check the file size from inside a function - javascript

So I have these Jquery code where the function will check the file extension and the file size from the input file. The checking for the file extension works fine, but the file size checking is not working, can you guys help me with this problem?
$(document).ready(function () {
/* Some other code
*/
var fileExtension = ['jpeg', 'jpg', 'png', 'pdf'];
var status = false;
function checkFile(fileinput){
if ($.inArray(fileinput.split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Tolong upload file dengan extensi: " + fileExtension.join(', '));
fileinput.value = "";
return status = false;
}
if (fileinput[0].size > 1048576) {
alert("The maximum file size is 1 mb");
fileinput.value = "";
return status = false;
}
else {
return status = true;
}
}
$('#btn_IdentitasKTP\\/Paspor').on('click', function () {
$('#file_IdentitasKTP\\/Paspor').trigger('click')
});
$('#file_IdentitasKTP\\/Paspor').change(function () {
var fileinput = $('#file_IdentitasKTP\\/Paspor').val();
checkFile(fileinput);
if (status == true) {
var file_name = this.value.replace(/\\/g, '/').replace(/.*\//, '');
$('#text_IdentitasKTP\\/Paspor').val(file_name);
status = false;
}
});
});

Try this :
$('#file_IdentitasKTP\\/Paspor').change(function () {
var fileinput = this.files;
...
you can check file size by :
console.log(fileinput[0].size)

For example to upload image by AJAX. You will simply write this code. You will size with object. it will return size of that object.
$(document).ready(function(e) {
$("#uploadimage").on('submit', (function(e) {
e.preventDefault();
formdata = new FormData(this);
if (formdata[0].size = < 1000) {
$.ajax({
url: "PHp File name path", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: formdata, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
} else {
alert("You can not Upload this file Please resize this image.")
}
}));

This is the updated code for this question.
$(document).ready(function () {
/* Some other code
*/
var fileExtension = ['jpeg', 'jpg', 'png', 'pdf'];
var status = false;
function checkFile(fileinput){
if ($.inArray(fileinput[0].name.split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Tolong upload file dengan extensi: " + fileExtension.join(', '));
fileinput.value = "";
return status = false;
}
if (fileinput[0].size > 1048576) {
alert("Tolong upload file dengan ukuran dibawah 1mb");
fileinput.value = "";
return status = false;
}
else {
return status = true;
}
}
$('#btn_IdentitasKTP\\/Paspor').on('click', function () {
$('#file_IdentitasKTP\\/Paspor').trigger('click')
});
$('#file_IdentitasKTP\\/Paspor').change(function () {
var fileinput = this.files;
checkFile(fileinput);
if (status == true) {
var file_name = this.value.replace(/\\/g, '/').replace(/.*\//, '');
$('#text_IdentitasKTP\\/Paspor').val(file_name);
status = false;
}
});
});

Related

how to change the parent location window when successfully checking using jquery

I have a problem in my code. I make a simple form using the checkbox. when the checkbox is clicked, the data will be validated. then if validation is successful then the checkbox will still be checked and window.location will change, if it fails, the checkbox will be unchecked and window.location will change.
$(document).ready(function () {
$(".publish").click(function () {
var data = $(this).attr("data-identity");
if ($(this).attr('checked', true)) {
var url = "/Manager/AdminApprove/";
}
$.ajax({
url: url + data
}).done(function (data) { //refresh after click
$(document).change(function () {
if ($(".publish").prop('checked', true)) { //if data succes validation
var error_succes = "Succes";
}
else {
var error_succes = "Error";
}
window.parent.location = "/Manager/Admin?" + error_succes;
});
});
});
});
var error_succes = "";
if (data == "True"){
var error_succes = "Succes";
}
else {
var error_succes = "Error";
}
window.parent.location = "/Manager/Admin?" + error_succes;

replace() in cropper js

My project is about saving the cropped image and show it in the view.
in my form when i cropped the image it works, but when i want to change the image so i crop it again and save. it create two rows with same image.
and when i change the image 3 times it create 3 rows with the same image and so on.
there is method called replace() that i have to use but i dont know how to use it.
this is my code
window.addEventListener('DOMContentLoaded', function () {
var avatar = document.getElementById('avatar');
var image = document.getElementById('image');
var input = document.getElementById('input');
var $progress = $('.progress');
var $progressBar = $('.progress-bar');
var $alert = $('.alert');
var $modal = $('#modal');
var cropper;
var title = $('#title');
var description = $('#description');
var arabic_title = $('#arabic_title');
var arabic_description = $('#arabic_description');
$('[data-toggle="tooltip"]').tooltip();
input.addEventListener('change', function (e) {
var files = e.target.files;
var done = function (url) {
input.value = '';
image.src = url;
// $alert.hide();
$modal.modal('show');
};
var reader;
var file;
var url;
if (files && files.length > 0) {
file = files[0];
if (FileReader) {
reader = new FileReader();
reader.onload = function (e) {
done(reader.result);
console.log('ok2');
};
reader.readAsDataURL(file);
console.log('ok3');
}
}
});
$modal.on('shown.bs.modal', function () {
cropper = new Cropper(image, {
aspectRatio: 1.7,
viewMode: 3,
});
}).on('hidden.bs.modal', function () {
cropper.destroy();
cropper = null;
});
document.getElementById('crop').addEventListener('click', function () {
var initialAvatarURL;
var canvas;
$modal.modal('hide');
if (cropper) {
canvas = cropper.getCroppedCanvas({
width: 400,
height: 400,
});
initialAvatarURL = avatar.src;
avatar.src = canvas.toDataURL();
$progress.show();
$alert.removeClass('alert-success alert-warning');
document.getElementById('save').addEventListener('click', function () {
canvas.toBlob(function (blob) {
var formData = new FormData();
formData.append('avatar', blob);
formData.append('title', title.val());
formData.append('description', description.val());
formData.append('arabic_title', arabic_title.val());
formData.append('arabic_description', arabic_description.val());
if (title.val() !== '' && description.val() !== '' && arabic_title.val() !== '' && arabic_description.val() !== '') {
for (let pair of formData.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax("{{url('admin/services')}}", {
method: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function () {
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function (e) {
var percent = '0';
var percentage = '0%';
if (e.lengthComputable) {
percent = Math.round((e.loaded / e.total) * 100);
percentage = percent + '%';
$progressBar.width(percentage).attr('aria-valuenow', percent).text(percentage);
}
};
return xhr;
},
success: function (data) {
$alert.show().addClass('alert-success').text('Upload success');
console.log(data);
},
error: function (error) {
avatar.src = initialAvatarURL;
$alert.show().addClass('alert-warning').text('Upload error');
console.log(error);
},
complete: function () {
$progress.hide();
},
});
}
});
});
}
});
});
$service = 'No service';
if (isset($_FILES['img'])) {
$service = Service::create(['title'=>$request->title,
'description'=>$request->description,
'photo'=>$request->img]);
}
return $service;
Try this.
Your Form Should Be
<form action="files/upload" method="post" enctype="multipart/form-data">
<input type="file" name="photo"/>
</form
Your Controller Should Be like
if ($request->hasFile('photo')) {
// move file upload here
}

Get the name of the uploaded file

I am new to AngularJS1 and Js. Here i am uploading a file which will be saved on my drive as well as in mongodb. What I am trying to do is to get the uploaded file name which can easily be seen here in attached picture. Kindly help me out with this.
$scope.uploadedFileList.push(p);
$('#addproFile').ajaxfileupload({
action: 'http://' + window.location.hostname + ':' + window.location.port + '/api/upload',
valid_extensions : ['md','csv','css', 'txt'],
params: {
dummy_name: p
},
onComplete: function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
/* $scope.nameString = uploadedFileList.join(',');
$scope.$apply();*/
},
onCancel: function() {
console.log('no file selected');
}
});
This is my controller
(function($) {
$.fn.ajaxfileupload = function(options) {
var settings = {
params: {},
action: '',
onStart: function() { },
onComplete: function(response) { },
onCancel: function() { },
validate_extensions : true,
valid_extensions : ['gif','png','jpg','jpeg'],
submit_button : null
};
var uploading_file = false;
if ( options ) {
$.extend( settings, options );
}
// 'this' is a jQuery collection of one or more (hopefully)
// file elements, but doesn't check for this yet
return this.each(function() {
var $element = $(this);
// Skip elements that are already setup. May replace this
// with uninit() later, to allow updating that settings
if($element.data('ajaxUploader-setup') === true) return;
$element.change(function()
{
// since a new image was selected, reset the marker
uploading_file = false;
// only update the file from here if we haven't assigned a submit button
if (settings.submit_button == null)
{
upload_file();
}
});
if (settings.submit_button == null)
{
// do nothing
} else
{
settings.submit_button.click(function(e)
{
// Prevent non-AJAXy submit
e.preventDefault();
// only attempt to upload file if we're not uploading
if (!uploading_file)
{
upload_file();
}
});
}
var upload_file = function()
{
if($element.val() == '') return settings.onCancel.apply($element, [settings.params]);
// make sure extension is valid
var ext = $element.val().split('.').pop().toLowerCase();
if(true == settings.validate_extensions && $.inArray(ext, settings.valid_extensions) == -1)
{
// Pass back to the user
settings.onComplete.apply($element, [{status: false, message: 'The select file type is invalid. File must be ' + settings.valid_extensions.join(', ') + '.'}, settings.params]);
} else
{
uploading_file = true;
// Creates the form, extra inputs and iframe used to
// submit / upload the file
wrapElement($element);
// Call user-supplied (or default) onStart(), setting
// it's this context to the file DOM element
var ret = settings.onStart.apply($element, [settings.params]);
// let onStart have the option to cancel the upload
if(ret !== false)
{
$element.parent('form').submit(function(e) { e.stopPropagation(); }).submit();
} else {
uploading_file = false;
}
}
};
// Mark this element as setup
$element.data('ajaxUploader-setup', true);
/*
// Internal handler that tries to parse the response
// and clean up after ourselves.
*/
var handleResponse = function(loadedFrame, element) {
var response, responseStr = $(loadedFrame).contents().text();
try {
//response = $.parseJSON($.trim(responseStr));
response = JSON.parse(responseStr);
} catch(e) {
response = responseStr;
}
// Tear-down the wrapper form
element.siblings().remove();
element.unwrap();
uploading_file = false;
// Pass back to the user
settings.onComplete.apply(element, [response, settings.params]);
};
/*
// Wraps element in a <form> tag, and inserts hidden inputs for each
// key:value pair in settings.params so they can be sent along with
// the upload. Then, creates an iframe that the whole thing is
// uploaded through.
*/
var wrapElement = function(element) {
// Create an iframe to submit through, using a semi-unique ID
var frame_id = 'ajaxUploader-iframe-' + Math.round(new Date().getTime() / 1000)
$('body').after('<iframe width="0" height="0" style="display:none;" name="'+frame_id+'" id="'+frame_id+'"/>');
$('#'+frame_id).get(0).onload = function() {
handleResponse(this, element);
};
// Wrap it in a form
element.wrap(function() {
return '<form action="' + settings.action + '" method="POST" enctype="multipart/form-data" target="'+frame_id+'" />'
})
// Insert <input type='hidden'>'s for each param
.before(function() {
var key, html = '';
for(key in settings.params) {
var paramVal = settings.params[key];
if (typeof paramVal === 'function') {
paramVal = paramVal();
}
html += '<input type="hidden" name="' + key + '" value="' + paramVal + '" />';
}
return html;
});
}
});
}
})( jQuery )
this is my ajax file upload function

how do I get my Ajax to return a function and prevent my document from downloading onclick

I have been trying to figure this out for hours.
I have the following document path on and anchor tag
#link.Title
I do not want to process the href if the "checkAuth" function returns a false.
Here is the "checkAuth" code.
var checkAuth = function(id, PasswordProtected) {
var result = null;
var hostname = location.hostname;
var host = '#System.Configuration.ConfigurationManager.AppSettings["hostroot"]';
if (hostname == "localhost")
host = "";
if (PasswordProtected == "1"){
var pass = prompt("This document is password protected", "");
var response = $.ajax({
type: "GET",
url: host + "/Communities/DeCryptPwd/",
data: {"id": id, "password": pass},
success: function (data) {
alert(data);
if (data == "True")
result = true;
if (data == "False")
result = false;
},
error: function (errorData) { alert(errorData); }
});
}
I just don't know how to stop the processing of the document on the href and return a true ... continue process, or false -- stop processing.
Just in case you need it, here is the "sever side" code called by the .ajax
public bool DeCryptPwd(int id, string password) {
var encrypted = db.CommunityDocs.Where(x => x.Id == id).Select(x => x.Password).SingleOrDefault();
/* Extract the bytes */
byte[] hashBytes = Convert.FromBase64String(encrypted);
/* Get the salt */
byte[] salt = new byte[16];
Array.Copy(hashBytes, 0, salt, 0, 16);
/* Compute the hash on the password the user entered */
var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000);
byte[] hash = pbkdf2.GetBytes(20);
/* Compare the results */
for (int i = 0; i < 20; i++)
if (hashBytes[i + 16] != hash[i])
return false;
return true;
}
You cannot return the result from an async function from the function that contains it. So you need to change the location in the success part and return true if not protected.
However the code will currently allow them to right-click and open in new window regardless
function checkAuth = function(theLink) {
var id = theLink.id,
protected = theLink.getAttribute("pass") == "1",
href = theLink.href,
result = null,
hostname = location.hostname,
host = '#System.Configuration.ConfigurationManager.AppSettings["hostroot"]';
if (hostname == "localhost")
host = "";
if (protected) {
var pass = prompt("This document is password protected", "");
var response = $.ajax({
type: "GET",
url: host + "/Communities/DeCryptPwd/",
data: {
"id": id,
"password": pass
},
success: function(data) {
alert(data);
if (data == "True") {
location = href;
}
},
error: function(errorData) {
alert(errorData);
}
});
return !protected; // return false if protected
}
#link.Title

Jquery limit user upload to 5 posts every minute

I have got this jquery/ajax
var uploaded=0;
if (uploaded!=0) {
setInterval(function() {
uploaded--;
}, 60000);
alert(uploaded);
}
$(".UploadMSub").click(function(event){
event.preventDefault();
var form_data = new FormData($('.SubmUploadFu')[0]);
if (uploaded<=5) {
$.ajax({
url: '../connect.php',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data)
{
var json_x = $.parseJSON(data);
var classRes = json_x[0].substring(0, 1);
$(".Result").html(json_x[0]).addClass(classRes).fadeIn(500).delay(2500).fadeOut(500,function() {
$(this).removeClass(classRes);
});
$(".Posts").children(".NumberOf").html(json_x[1]);
$(".Text").val("");
$("#Nameupload").val("");
$(".PhotShow").slideUp(500);
uploaded++;
}
});
}else{
$(".Result").html("You can upload up to 5 posts in one minute").addClass("E").fadeIn(500).delay(2500).fadeOut(500);
}
});
And this php
function isFileUploadAllowed() {
$isAllowed = true;
$timeNow = time();
$timeFrameInSeconds = 30;
$maxUploadsInTimeFrame = 5;
$firstUploadTime = $_SESSION['firstUploadTime'] ? intval($_SESSION['firstUploadTime']) : $timeNow;
$numberOfUploadsInTimeFrame = $_SESSION['numberOfUploadsInTimeFrame'] ? intval($_SESSION['numberOfUploadsInTimeFrame']) : 0;
$givenTimeFrameExpired = (($firstUploadTime + $timeFrameInSeconds) < $timeNow);
if (!$givenTimeFrameExpired) {
if ($numberOfUploadsInTimeFrame + 1 > $maxUploadsInTimeFrame) {
$isAllowed = false;
}
}
if ($isAllowed === true) {
if ($givenTimeFrameExpired) {
$_SESSION['firstUploadTime'] = $timeNow;
$_SESSION['numberOfUploadsInTimeFrame'] = 0;
}
$_SESSION['numberOfUploadsInTimeFrame']++;
}
return $isAllowed;
}
if(isset($_POST['new_post'])){
$Text=htmlspecialchars($_POST['new_post'],ENT_QUOTES);
$Text=trim($Text);
if (is_uploaded_file($_FILES['Upload_f']['tmp_name'])) {
if (isFileUploadAllowed()) {
$fileP=$_FILES['Upload_f'];
$fileP_name=$fileP['name'];
$fileP_tmp=$fileP['tmp_name'];
$fileP_size=$fileP['size'];
$fileP_error=$fileP['error'];
$fileP_extension=explode('.', $fileP_name);
$fileP_extension=strtolower(end($fileP_extension));
$allowed=array('jpg','png');
if (in_array($fileP_extension, $allowed)){
if ($fileP_error===0) {
if ($fileP_size<=2097152){
$fileP_new_name=uniqid().'.'.$fileP_extension;
}
}
$NotInarray=false;
}else{
$fileP_new_name="";
$NotInarray=true;
}
$Fileuploaded=true;
}
}else{
$fileP_new_name="";
$fileP=0;
$Fileuploaded=false;
$NotInarray=false;
}
$Posts=$con->query("SELECT Posts FROM user_opt WHERE Username='$NameId'");
$row=$Posts->fetch_row();
if (strlen($Text)>400) {
$Res="Error occurred.Please try again";
$PostNum=$row[0];
}elseif(strlen($Text)==0 && $fileP==0){
$Res="Both fields are empty";
$PostNum=$row[0];
}elseif($Fileuploaded===true){
if ($NotInarray==true) {
$Res="Only jpg and png files are allowed";
$PostNum=$row[0];
}elseif ($fileP_error!=0) {
$Res="Error occurred.Please try again";
$PostNum=$row[0];
}else{
$Res="Success";
$PostNum=$row[0]+1;
}
}else{
$Rand=generateRandomString(100);
$query=$con->query("INSERT INTO uploads (Rand,Username,image,`Text`,`Date`) VALUES('$Rand','$NameId','$fileP_new_name','$Text',NOW())");
$querya=$con->query("UPDATE user_opt SET posts=posts+1 WHERE Username='$NameId'");
$PostNum=$row[0]+1;
$Res="Success";
}
echo json_encode(array($Res,$PostNum));
}
But the problem is when user uses dev tools he can easily change
if (uploaded<=5) {
To
if (uploaded<=50) {
And jquery will take increase limit to 50.How can i prevent that?
Also may the problem be in php function?Cause if my php function works properly it should not insert data into database but it does
You have no else clause for if (isFileUploadAllowed()), so you're not clearing the variables. You can combine that test with the outer test:
if (is_uploaded_file($_FILES['Upload_f']['tmp_name'] && isFileUploadAllowed())

Categories