I tried different approach but still can't find the solution.
I need to upload an image with my form with fields (title, description, and 2 image).
My system uses csrf of CodeIgniter. And I use this simple third party file uploader (http://jasny.github.io/bootstrap) fileinput.js
var Fileinput = function (element, options) {
this.$element = $(element)
this.$input = this.$element.find(':file')
if (this.$input.length === 0) return
this.name = this.$input.attr('name') || options.name
this.$hidden = this.$element.find('input[type=hidden][name="' + this.name + '"]')
if (this.$hidden.length === 0) {
this.$hidden = $('<input type="hidden">').insertBefore(this.$input)
}
this.$preview = this.$element.find('.fileinput-preview')
var height = this.$preview.css('height')
if (this.$preview.css('display') !== 'inline' && height !== '0px' && height !== 'none') {
this.$preview.css('line-height', height)
}
this.original = {
exists: this.$element.hasClass('fileinput-exists'),
preview: this.$preview.html(),
hiddenVal: this.$hidden.val()
}
this.listen()
}
Fileinput.prototype.listen = function() {
this.$input.on('change.bs.fileinput', $.proxy(this.change, this))
$(this.$input[0].form).on('reset.bs.fileinput', $.proxy(this.reset, this))
this.$element.find('[data-trigger="fileinput"]').on('click.bs.fileinput', $.proxy(this.trigger, this))
this.$element.find('[data-dismiss="fileinput"]').on('click.bs.fileinput', $.proxy(this.clear, this))
},
Fileinput.prototype.change = function(e) {
var files = e.target.files === undefined ? (e.target && e.target.value ? [{ name: e.target.value.replace(/^.+\\/, '')}] : []) : e.target.files
e.stopPropagation()
if (files.length === 0) {
this.clear()
return
}
this.$hidden.val('')
this.$hidden.attr('name', '')
this.$input.attr('name', this.name)
var file = files[0]
if (this.$preview.length > 0 && (typeof file.type !== "undefined" ? file.type.match(/^image\/(gif|png|jpeg)$/) : file.name.match(/\.(gif|png|jpe?g)$/i)) && typeof FileReader !== "undefined") {
var reader = new FileReader()
var preview = this.$preview
var element = this.$element
reader.onload = function(re) {
var $img = $('<img>')
$img[0].src = re.target.result
files[0].result = re.target.result
element.find('.fileinput-filename').text(file.name)
// if parent has max-height, using `(max-)height: 100%` on child doesn't take padding and border into account
if (preview.css('max-height') != 'none') $img.css('max-height', parseInt(preview.css('max-height'), 10) - parseInt(preview.css('padding-top'), 10) - parseInt(preview.css('padding-bottom'), 10) - parseInt(preview.css('border-top'), 10) - parseInt(preview.css('border-bottom'), 10))
preview.html($img)
element.addClass('fileinput-exists').removeClass('fileinput-new')
element.trigger('change.bs.fileinput', files)
}
reader.readAsDataURL(file)
} else {
this.$element.find('.fileinput-filename').text(file.name)
this.$preview.text(file.name)
this.$element.addClass('fileinput-exists').removeClass('fileinput-new')
this.$element.trigger('change.bs.fileinput')
}
},
Fileinput.prototype.clear = function(e) {
if (e) e.preventDefault()
this.$hidden.val('')
this.$hidden.attr('name', this.name)
this.$input.attr('name', '')
//ie8+ doesn't support changing the value of input with type=file so clone instead
this.$input.val('')
this.$preview.html('')
this.$element.find('.fileinput-filename').text('')
this.$element.addClass('fileinput-new').removeClass('fileinput-exists')
if (e !== undefined) {
this.$input.trigger('change')
this.$element.trigger('clear.bs.fileinput')
}
},
Fileinput.prototype.reset = function() {
this.clear()
this.$hidden.val(this.original.hiddenVal)
this.$preview.html(this.original.preview)
this.$element.find('.fileinput-filename').text('')
if (this.original.exists) this.$element.addClass('fileinput-exists').removeClass('fileinput-new')
else this.$element.addClass('fileinput-new').removeClass('fileinput-exists')
this.$element.trigger('reset.bs.fileinput')
},
Fileinput.prototype.trigger = function(e) {
this.$input.trigger('click')
e.preventDefault()
}
// FILEUPLOAD PLUGIN DEFINITION
// ===========================
var old = $.fn.fileinput
$.fn.fileinput = function (options) {
return this.each(function () {
var $this = $(this),
data = $this.data('bs.fileinput')
if (!data) $this.data('bs.fileinput', (data = new Fileinput(this, options)))
if (typeof options == 'string') data[options]()
})
}
$.fn.fileinput.Constructor = Fileinput
// FILEINPUT NO CONFLICT
// ====================
$.fn.fileinput.noConflict = function () {
$.fn.fileinput = old
return this
}
// FILEUPLOAD DATA-API
// ==================
$(document).on('click.fileinput.data-api', '[data-provides="fileinput"]', function (e) {
var $this = $(this)
if ($this.data('bs.fileinput')) return
$this.fileinput($this.data())
var $target = $(e.target).closest('[data-dismiss="fileinput"],[data-trigger="fileinput"]');
if ($target.length > 0) {
e.preventDefault()
$target.trigger('click.bs.fileinput')
}
});
Now here is my form:
<form id="default_form" onsubmit="return false;" data-method="websites" enctype="multipart/form-data" data-toastr-position="top-right" data-success="Sent! Thank you!" class="validate" novalidate="novalidate">
<input type="hidden" name="{$my_csrf_name}" id="csrf" value="{$my_csrf_value}" />
<input type="text" class="form-control required" value="" name="d[DEF_TITLE]" id="MY_TITLE">
<textarea class="form-control required" rows="3" name="d[MY_DESC]" id="MY_DESC"></textarea>
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new thumbnail" style="min-width: 160px; min-height: 100px; max-width: 200px; max-height: 150px; line-height: 10px;"> <img src="{$_homeurl}space/perm/img/favicon/{$set_data.MY_FAVICON}" alt="{$homeurl}space/perm/img/favicon/{$set_data.MY_FAVICON}" data-src="{$homeurl}space/perm/img/favicon/{$set_data.MY_FAVICON}" > </div>
<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;"></div>
<div>
<span class="btn btn-default btn-file" class="upload-image">
<span class="fileinput-new">Select Favicon image</span>
<span class="fileinput-exists">Change</span>
<input type="file" id="MY_FAVICON" name="d[MY_FAVICON]"></span>
Remove
</div>
</div>
<button id="submit_form" data-fid="default_form" class="btn btn-3d btn-primary btn-xlg btn-block margin-top-30" type="submit">
SUBMIT
</button>
</form>
Now upon clicking the "Select Favicon image" here is my js code event:
var csrf_val = $('#csrf').val();
var csfrData = {};
csfrData['csrf_name'] = csrf_val;
sendFile(this.files[0]);
function sendFile(file) {
$(function() {
$.ajaxSetup({
data: csfrData
});
});
$.ajax({
method: 'post',
url: _admin_url + _curr_mod+'/procedure/uload-image',
data: file,
success: function() {
alert('upload is ok!');
},
processData: false
});
}
upon select of image the JavaScript will process to upload the image in PHP controller/model. As I try to look into the Firebug the post has this values:
ÿØÿà�JFIF������ÿÛ��
Then in the response tab found in the CodeIgniter was this (this might be because of the csrf is not included in the post data):
An Error Was Encountered
The action you have requested is not allowed.
and for the php will just use this code (still not sure how will I handle it in php):
$_FILES['file']
I don't know how to upload an image using an uploader (that has preview of the file) and with csrf in CodeIgniter.
The process is this, upon select of image, an ajax will upload it to the server (temporary folder), and will return a new filename (encryption enabled upon upload in php)
Related
This is the Javascript that turns on Georgian keyboard in every input and textarea field
But I have one input field with ID user_login which type is text and of course, this javascript takes effect on this field too
I simply want to disable the effect of this javascript only for this field which ID is user_login
Please help me
thank you in advance
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="jquery.geokbd.css">
<script type="text/javascript" src="/js/jquery_min.js"></script>
<script type="text/javascript" src="jquery.geokbd.js"></script>
</head>
<body>
<div class="gk-switcher">
<input id="kbd-switcher" type="checkbox">
</div>
<form>
<input type="text" placeholder="Title">
<input type="text" placeholder="Description">
<input placeholder="Password" type="password">
<input placeholder="Email" type="email">
</form>
<input placeholder="Email" type="email">
<input placeholder="About me" maxlength="11" type="text">
<input placeholder="Username:" type="text" name="user_login" id="user_login" class="wide">
<script>
$('#kbd-switcher').geokbd();
</script>
</body>
</html>
and code
(function($, undefined) {
$.fn.geokbd = function(options) {
var
isOn,
inputs = $([]),
switchers = $([]),
defaults = {
on: true,
hotkey: '`'
},
settings = (typeof options === 'object' ? $.extend({}, defaults, options) : defaults);
// first come up with affected set of input elements
this.each(function() {
var $this = $(this);
if ($this.is(':text, textarea')) {
inputs = inputs.add($this);
} else if ($this.is('form')) {
inputs = inputs.add($this.find(':text, textarea'));
} else if ($this.is(':checkbox')) {
if (!inputs.length) {
inputs = $(':text, textarea');
}
switchers = switchers.add($this); // store the checkboxes for further manipulation
}
if (typeof settings.exclude === 'string') {
inputs = inputs.not(settings.exclude);
}
});
// mutate switchers
switchers
.click(function() { toggleLang() })
.wrap('<div class="gk-switcher"></div>')
.parent()
.append('<div class="gk-ka" /><div class="gk-us" />');
// turn on/off all switchers
toggleLang(isOn = settings.on);
$(document).keypress(function(e) {
var ch = String.fromCharCode(e.which), kach;
if (settings.hotkey === ch) {
toggleLang();
e.preventDefault();
}
if (!isOn || !inputs.filter(e.target).length) {
return;
}
kach = translateToKa.call(ch);
if (ch != kach) {
if (navigator.appName.indexOf("Internet Explorer")!=-1) {
window.event.keyCode = kach.charCodeAt(0);
} else {
pasteTo.call(kach, e.target);
e.preventDefault();
}
}
});
function toggleLang() {
isOn = arguments[0] !== undefined ? arguments[0] : !isOn;
switchers
.each(function() {
this.checked = isOn;
})
.closest('.gk-switcher')[isOn ? 'addClass' : 'removeClass']('gk-on');
}
// the following functions come directly from Ioseb Dzmanashvili's GeoKBD (https://github.com/ioseb/geokbd)
function translateToKa() {
/**
* Original idea by Irakli Nadareishvili
* http://www.sapikhvno.org/viewtopic.php?t=47&postdays=0&postorder=asc&start=10
*/
var index, chr, text = [], symbols = "abgdevzTiklmnopJrstufqRySCcZwWxjh";
for (var i = 0; i < this.length; i++) {
chr = this.substr(i, 1);
if ((index = symbols.indexOf(chr)) >= 0) {
text.push(String.fromCharCode(index + 4304));
} else {
text.push(chr);
}
}
return text.join('');
}
function pasteTo(field) {
field.focus();
if (document.selection) {
var range = document.selection.createRange();
if (range) {
range.text = this;
}
} else if (field.selectionStart != undefined) {
var scroll = field.scrollTop, start = field.selectionStart, end = field.selectionEnd;
var value = field.value.substr(0, start) + this + field.value.substr(end, field.value.length);
field.value = value;
field.scrollTop = scroll;
field.setSelectionRange(start + this.length, start + this.length);
} else {
field.value += this;
field.setSelectionRange(field.value.length, field.value.length);
}
};
}
}(jQuery));
If you call your plugin on the form element, instead of the checkbox and then search the document for all desired element types except the one with the id of user_login, your inputs JQuery wrapper will only contain the elements you want.
(function($, undefined) {
$.fn.geokbd = function(options) {
var
isOn,
inputs = $([]),
switchers = $([]),
defaults = {
on: true,
hotkey: '`'
},
settings = (typeof options === 'object' ? $.extend({}, defaults, options) : defaults);
// first come up with affected set of input elements
// Using the standard DOM API, search the document for all `input` and
// 'textarea' elements, except for the one with an id of: "user_login"
document.querySelectorAll("input:not(#user_login), textarea").forEach(function(item) {
var $this = $(item);
// You had the selector for an input incorrect
if ($this.is('input[type="text"], textarea')) {
inputs = inputs.add($this);
} else if ($this.is('form')) {
inputs = inputs.add($this.find('input[type="text"], textarea'));
} else if ($this.is(':checkbox')) {
if (!inputs.length) {
inputs = $('input[type="text"], textarea');
}
switchers = switchers.add($this); // store the checkboxes for further manipulation
}
if (typeof settings.exclude === 'string') {
inputs = inputs.not(settings.exclude);
}
});
// mutate switchers
switchers
.click(function() { toggleLang() })
.wrap('<div class="gk-switcher"></div>')
.parent()
.append('<div class="gk-ka" /><div class="gk-us" />');
// turn on/off all switchers
toggleLang(isOn = settings.on);
$(document).keypress(function(e) {
var ch = String.fromCharCode(e.which), kach;
if (settings.hotkey === ch) {
toggleLang();
e.preventDefault();
}
if (!isOn || !inputs.filter(e.target).length) {
return;
}
kach = translateToKa.call(ch);
if (ch != kach) {
if (navigator.appName.indexOf("Internet Explorer")!=-1) {
window.event.keyCode = kach.charCodeAt(0);
} else {
pasteTo.call(kach, e.target);
e.preventDefault();
}
}
});
function toggleLang() {
isOn = arguments[0] !== undefined ? arguments[0] : !isOn;
switchers
.each(function() {
this.checked = isOn;
})
.closest('.gk-switcher')[isOn ? 'addClass' : 'removeClass']('gk-on');
}
// the following functions come directly from Ioseb Dzmanashvili's GeoKBD (https://github.com/ioseb/geokbd)
function translateToKa() {
/**
* Original idea by Irakli Nadareishvili
* http://www.sapikhvno.org/viewtopic.php?t=47&postdays=0&postorder=asc&start=10
*/
var index, chr, text = [], symbols = "abgdevzTiklmnopJrstufqRySCcZwWxjh";
for (var i = 0; i < this.length; i++) {
chr = this.substr(i, 1);
if ((index = symbols.indexOf(chr)) >= 0) {
text.push(String.fromCharCode(index + 4304));
} else {
text.push(chr);
}
}
return text.join('');
}
function pasteTo(field) {
field.focus();
if (document.selection) {
var range = document.selection.createRange();
if (range) {
range.text = this;
}
} else if (field.selectionStart != undefined) {
var scroll = field.scrollTop, start = field.selectionStart, end = field.selectionEnd;
var value = field.value.substr(0, start) + this + field.value.substr(end, field.value.length);
field.value = value;
field.scrollTop = scroll;
field.setSelectionRange(start + this.length, start + this.length);
} else {
field.value += this;
field.setSelectionRange(field.value.length, field.value.length);
}
};
}
$('form').geokbd();
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="jquery.geokbd.css">
</head>
<body>
<div class="gk-switcher">
<input id="kbd-switcher" type="checkbox">
</div>
<form>
<input type="text" placeholder="Title">
<input type="text" placeholder="Description">
<input placeholder="Password" type="password">
<input placeholder="Email" type="email">
</form>
<input placeholder="Email" type="email">
<input placeholder="About me" maxlength="11" type="text">
<input placeholder="Username:" type="text" name="user_login" id="user_login" class="wide">
</body>
</html>
Cropper.js aspect ratio buttons not working. Whenever I tried to upload an image and try to press the 16:9 button then my images will be invisible and not cropped and reinitiate. after that when I again select the image at that time I will see effect of my button.
https://fengyuanchen.github.io/jquery-cropper/
Cropper-init.js
$(function () {
'use strict';
var console = window.console || { log: function () {} };
var $image = $('#image');
var $download = $('#download');
var $dataX = $('#dataX');
var $dataY = $('#dataY');
var $dataHeight = $('#dataHeight');
var $dataWidth = $('#dataWidth');
var $dataRotate = $('#dataRotate');
var $dataScaleX = $('#dataScaleX');
var $dataScaleY = $('#dataScaleY');
var options = {
aspectRatio: 16 / 9,
preview: '.img-preview',
crop: function (e) {
$dataX.val(Math.round(e.x));
$dataY.val(Math.round(e.y));
$dataHeight.val(Math.round(e.height));
$dataWidth.val(Math.round(e.width));
$dataRotate.val(e.rotate);
$dataScaleX.val(e.scaleX);
$dataScaleY.val(e.scaleY);
}
};
// Tooltip
$('[data-toggle="tooltip"]').tooltip();
// Cropper
$image.on({
'build.cropper': function (e) {
// console.log(e.type);
},
'built.cropper': function (e) {
// console.log(e.type);
},
'cropstart.cropper': function (e) {
// console.log(e.type, e.action);
},
'cropmove.cropper': function (e) {
// console.log(e.type, e.action);
},
'cropend.cropper': function (e) {
// console.log(e.type, e.action);
},
'crop.cropper': function (e) {
// console.log(e.type, e.x, e.y, e.width, e.height, e.rotate, e.scaleX, e.scaleY);
$('#img_btn').prop("disabled", false);
},
'zoom.cropper': function (e) {
// console.log(e.type, e.ratio);
}
}).cropper(options);
// Buttons
if (!$.isFunction(document.createElement('canvas').getContext)) {
$('button[data-method="getCroppedCanvas"]').prop('disabled', true);
}
if (typeof document.createElement('cropper').style.transition === 'undefined') {
$('button[data-method="rotate"]').prop('disabled', true);
$('button[data-method="scale"]').prop('disabled', true);
}
// Download
// if (typeof $download[0].download === 'undefined') {
// $download.addClass('disabled');
// }
// Options
$('.docs-toggles').on('change', 'input', function () {
var $this = $(this);
var name = $this.attr('name');
var type = $this.prop('type');
var cropBoxData;
var canvasData;
if (!$image.data('cropper')) {
return;
}
if (type === 'checkbox') {
options[name] = $this.prop('checked');
cropBoxData = $image.cropper('getCropBoxData');
canvasData = $image.cropper('getCanvasData');
options.built = function () {
$image.cropper('setCropBoxData', cropBoxData);
$image.cropper('setCanvasData', canvasData);
};
} else if (type === 'radio') {
options[name] = $this.val();
}
$image.cropper('destroy').cropper(options);
});
// Methods
$('.docs-buttons').on('click', '[data-method]', function () {
var $this = $(this);
var data = $this.data();
var $target;
var result;
if ($this.prop('disabled') || $this.hasClass('disabled')) {
return;
}
if ($image.data('cropper') && data.method) {
data = $.extend({}, data); // Clone a new one
if (typeof data.target !== 'undefined') {
$target = $(data.target);
if (typeof data.option === 'undefined') {
try {
data.option = JSON.parse($target.val());
} catch (e) {
// console.log(e.message);
}
}
}
if (data.method === 'rotate') {
$image.cropper('clear');
}
result = $image.cropper(data.method, data.option, data.secondOption);
if (data.method === 'rotate') {
$image.cropper('crop');
}
switch (data.method) {
case 'scaleX':
case 'scaleY':
$(this).data('option', -data.option);
break;
case 'getCroppedCanvas':
if (result) {
// Bootstrap's Modal
$('#getCroppedCanvasModal').modal().find('.modal-body').html(result);
if (!$download.hasClass('disabled')) {
$download.attr('href', result.toDataURL('image/jpeg'));
}
}
break;
}
if ($.isPlainObject(result) && $target) {
try {
$target.val(JSON.stringify(result));
} catch (e) {
// console.log(e.message);
}
}
}
});
// Keyboard
$(document.body).on('keydown', function (e) {
if (!$image.data('cropper') || this.scrollTop > 300) {
return;
}
switch (e.which) {
case 37:
e.preventDefault();
$image.cropper('move', -1, 0);
break;
case 38:
e.preventDefault();
$image.cropper('move', 0, -1);
break;
case 39:
e.preventDefault();
$image.cropper('move', 1, 0);
break;
case 40:
e.preventDefault();
$image.cropper('move', 0, 1);
break;
}
});
// Import image
var $inputImage = $('.input-image');
var URL = window.URL || window.webkitURL;
var blobURL;
if (URL) {
$inputImage.change(function () {
var files = this.files;
var file;
if (!$image.data('cropper')) {
return;
}
if (files && files.length) {
file = files[0];
if (/^image\/\w+$/.test(file.type)) {
blobURL = URL.createObjectURL(file);
$image.one('built.cropper', function () {
// Revoke when load complete
URL.revokeObjectURL(blobURL);
}).cropper('reset').cropper('replace', blobURL);
} else {
$inputImage.val('');
$('#formUploadImage').bootstrapValidator('revalidateField', 'inputImage');
$('#image').cropper('destroy').cropper({
aspectRatio: 1 / 1,
viewMode: 1
});
window.alert('Please choose an image file.');
}
}
});
} else {
$inputImage.prop('disabled', true).parent().addClass('disabled');
}
});
HTML
<input type="file" id="inputImage" name="inputImage" accept=".jpg,.jpeg,.png" class="form-control input-image" />
<div class="docs-toggles btn-group btn-group-justified" data-toggle="buttons">
<label class="btn btn-default btn-outline active">
<input type="radio" class="sr-only" id="aspectRatio0" name="aspectRatio" value="1.7777777777777777">
<span class="docs-tooltip" data-toggle="tooltip" title="aspectRatio: 16 / 9"> 16:9 </span> </label>
<label class="btn btn-default btn-outline">
<input type="radio" class="sr-only" id="aspectRatio1" name="aspectRatio" value="1.3333333333333333">
<span class="docs-tooltip" data-toggle="tooltip" title="aspectRatio: 4 / 3"> 4:3 </span> </label>
<label class="btn btn-default btn-outline">
<input type="radio" class="sr-only" id="aspectRatio2" name="aspectRatio" value="1">
<span class="docs-tooltip" data-toggle="tooltip" title="aspectRatio: 1 / 1"> 1:1 </span> </label>
<label class="btn btn-default btn-outline">
<input type="radio" class="sr-only" id="aspectRatio3" name="aspectRatio" value="0.6666666666666666">
<span class="docs-tooltip" data-toggle="tooltip" title="aspectRatio: 2 / 3"> 2:3 </span> </label>
</div>
I need to change the background image inside of canvas with the leimi drawingboard.js, but I have no idea how to make it.
I need to show different images so that the user can choose between them with which he is going to work
Here is my form:
<div id="container">
<div class="example" data-example="1"> // THIS DIV IS THE CANVAS
<div class="board" id="default-board"></div> //THIS ID HAVE A IMAGE AND THE CONTROLLERS
</div>
<form class="drawing-form" method="post" name="diagram" id="diagram" enctype="multipart/form-data">
<div id="board"></div>
<input type="hidden" name="image" value="">
<input type="hidden" name="idPac" value="<?php echo $id_paciente; ?>" />
<input type="hidden" name="idDoc" value="<?php echo $user_id; ?>" />
<br><hr>
<button class="btn btn-info" id="btnUpload"><?php $translate->__('Save Diagram'); ?></button>
</form>
<div id="ldiag" style="display:none;"><img src="images/loading4.gif" /></div>
</div>
And the javascript code is:
<script src="js/drawingboard.min.js"></script>
<script data-example="1">
var defaultBoard = new DrawingBoard.Board("default-board", {
background: "imagenes/canvas/cara.jpg", //THIS IS THE IMAGE I NEED TO CHANGE FOR OTHERS IF NEEDED, EXAMPLE /pie.png, /cuerpo.png
droppable: true,
webStorage: false,
enlargeYourContainer: true,
addToBoard: true,
stretchImg: false
});
defaultBoard.addControl("Download");
$(".drawing-form").on("submit", function(e) {
var img = defaultBoard.getImg();
var imgInput = (defaultBoard.blankCanvas == img) ? "" : img;
$(this).find("input[name=image]").val( imgInput );
defaultBoard.clearWebStorage();
});
$(function() {
$("#file-input").change(function(e) {
var file = e.target.files[0],
imageType = /image.*/;
if (!file.type.match(imageType))
return;
var reader = new FileReader();
reader.onload = fileOnload;
reader.readAsDataURL(file);
});
function fileOnload(e) {
var $img = $("<img>", { src: e.target.result });
var canvas = $("#default-board")[0];
var context = canvas.getContext("2d");
$img.load(function() {
context.drawImage(this, 0, 0);
});
}
});
</script>
<script src="js/yepnope.js"></script>
<script>
var iHasRangeInput = function() {
var inputElem = document.createElement("input"),
smile = ":)",
docElement = document.documentElement,
inputElemType = "range",
available;
inputElem.setAttribute("type", inputElemType);
available = inputElem.type !== "text";
inputElem.value = smile;
inputElem.style.cssText = "position:absolute;visibility:hidden;";
if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) {
docElement.appendChild(inputElem);
defaultView = document.defaultView;
available = defaultView.getComputedStyle &&
defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== "textfield" &&
(inputElem.offsetHeight !== 0);
docElement.removeChild(inputElem);
}
return !!available;
};
yepnope({
test : iHasRangeInput(),
nope : ["css/fd-slider.min.css", "js/fd-slider.min.js"],
callback: function(id, testResult) {
if("fdSlider" in window && typeof (fdSlider.onDomReady) != "undefined") {
try { fdSlider.onDomReady(); } catch(err) {}
}
}
});
</script>
I have a JavaScript function that shows me the previews of the images I want to upload to the server. After recieving that previews I can select some of them by clicking and remove previews, but I need also to remove the selected files so they will not be uploaded to the server.
The following code can remove the previews but not the files. How can it be improved?
JavaScript:
$(document).ready(function () {
$("#image-holder").on('click', '.thumb-image', function () {
$(this).toggleClass("selectedItem");
});
$("#btnDelete").on("click", function () {
$(".selectedItem").remove();
});
$("#fileUpload").on('change', function () {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#image-holder");
image_holder.empty();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof(FileReader) != "undefined") {
//loop for each file selected for uploading.
for (var i = 0; i < countFiles; i++) {
var reader = new FileReader();
reader.onload = function (e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
};
image_holder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Please select only images");
}
});
});
HTML:
<form method="POST" action="upload" enctype="multipart/form-data">
<input id="fileUpload" name="file" multiple="multiple" type="file"/>
<br/>
<input type="submit" value="Upload">
</form>
<button id="btnDelete">Delete</button>
I've done this before using AngularJS. In that case I just had to set the ng-model variable to undefined. I haven't tested this, but you should be able to accomplish the same thing by clearing your <input> value in a similar way.
$("#btnDelete").on("click", function () {
$(".selectedItem").remove();
$("#fileUpload").get(0).files[0] = undefined;
$("#fileUpload").removeAttr('value');
});
I am triggering a file upload on href click.
I am trying to block all extension except doc, docx and pdf.
I am not getting the correct alert value.
<div class="cv"> Would you like to attach you CV? Click here</div>
<input type="file" id="resume" style="visibility: hidden">
Javascript:
var myfile="";
$('#resume_link').click(function() {
$('#resume').trigger('click');
myfile=$('#resume').val();
var ext = myfile.split('.').pop();
//var extension = myfile.substr( (myfile.lastIndexOf('.') +1) );
if(ext=="pdf" || ext=="docx" || ext=="doc"){
alert(ext);
}
else{
alert(ext);
}
})
MyFiddle..its showing error
You can use
<input name="Upload Saved Replay" type="file"
accept="application/pdf,application/msword,
application/vnd.openxmlformats-officedocument.wordprocessingml.document"/>
whearat
application/pdf means .pdf
application/msword means .doc
application/vnd.openxmlformats-officedocument.wordprocessingml.document means .docx
instead.
[EDIT] Be warned, .dot might match too.
Better to use change event on input field.
Updated source:
var myfile="";
$('#resume_link').click(function( e ) {
e.preventDefault();
$('#resume').trigger('click');
});
$('#resume').on( 'change', function() {
myfile= $( this ).val();
var ext = myfile.split('.').pop();
if(ext=="pdf" || ext=="docx" || ext=="doc"){
alert(ext);
} else{
alert(ext);
}
});
Updated jsFiddle.
For only acept files with extension doc and docx in the explorer window try this
<input type="file" id="docpicker"
accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
Below code worked for me:
<input #fileInput type="file" id="avatar" accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" />
application/pdf means .pdf
application/msword means .doc
application/vnd.openxmlformats-officedocument.wordprocessingml.document means .docx
Try this
$('#resume_link').click(function() {
var ext = $('#resume').val().split(".").pop().toLowerCase();
if($.inArray(ext, ["doc","pdf",'docx']) == -1) {
// false
}else{
// true
}
});
Hope it will help
var file = form.getForm().findField("file").getValue();
var fileLen = file.length;
var lastValue = file.substring(fileLen - 3, fileLen);
if (lastValue == 'doc') {//check same for other file format}
$('#surat_lampiran').bind('change', function() {
alerr = "";
sts = false;
alert(this.files[0].type);
if(this.files[0].type != "application/pdf" && this.files[0].type != "application/msword" && this.files[0].type != "application/vnd.openxmlformats-officedocument.wordprocessingml.document"){
sts = true;
alerr += "Jenis file bukan .pdf/.doc/.docx ";
}
});
You can simply make it by REGEX:
Form:
<form method="post" action="" enctype="multipart/form-data">
<div class="uploadExtensionError" style="display: none">Only PDF allowed!</div>
<input type="file" name="item_file" />
<input type="submit" id='submit' value="submit"/>
</form>
And java script validation:
<script>
$('#submit').click(function(event) {
var val = $('input[type=file]').val().toLowerCase();
var regex = new RegExp("(.*?)\.(pdf|docx|doc)$");
if(!(regex.test(val))) {
$('.uploadExtensionError').show();
event.preventDefault();
}
});
</script>
Cheers!
if(req.file){
let img = req.file ;
if(img.mimetype != "application/pdf" && img.mimetype != "application/msword" && img.mimetype != "application/vnd.openxmlformats-officedocument.wordprocessingml.document"){
throw {message :"Please enter only pdf and docx file"}
}
}
HTML code:
<input type="file" multiple={true} id="file" onChange={this.addFile.bind(this)} accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.ppt, .pptx"/>
React code - file attached and set files in state:
#autobind
private addFile(event) {
for(var j=0;j<event.target.files.length;j++){
var _size = event.target.files[j].size;
var fSExt = new Array('Bytes', 'KB', 'MB', 'GB'),
i=0;while(_size>900){_size/=1024;i++;}
var exactSize = (Math.round(_size*100)/100)+' '+fSExt[i];
var date = event.target.files[0].lastModifiedDate,
mnth = ("0" + (date.getMonth() + 1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
date=[day,mnth,date.getFullYear()].join("/");
fileinformation.push({
"file_name": event.target.files[j].name,
"file_size": exactSize,
"file_modified_date":date
});
var ext = event.target.files[j].name.split('.').pop();
if(ext=="pdf" || ext=="docx" || ext=="doc"|| ext=="ppt"|| ext=="pptx"){
} else{
iscorrectfileattached=false;
}
}
if(iscorrectfileattached==false){
alert("Only PFD, Word and PPT file can be attached.");
return false;
}
this.setState({fileinformation});
//new code end
var date = event.target.files[0].lastModifiedDate,
mnth = ("0" + (date.getMonth() + 1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
date=[day,mnth,date.getFullYear()].join("/");
this.setState({filesize:exactSize});
this.setState({filedate:date});
//let resultFile = document.getElementById('file');
let resultFile = event.target.files;
console.log(resultFile);
let fileInfos = [];
for (var i = 0; i < resultFile.length; i++) {
var fileName = resultFile[i].name;
console.log(fileName);
var file = resultFile[i];
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
//Push the converted file into array
fileInfos.push({
"name": file.name,
"content": e.target.result
});
};
})(file);
reader.readAsArrayBuffer(file);
}
this.setState({fileInfos});
this.setState({FileNameValue: event.target.files[0].name });
//this.setState({IsDisabled: true });//for multiple file
console.log(fileInfos);
}