How to clear HttpPostedFileBase with jquery if image isn't valid - javascript

I want to set my file input element to null if the file isn't a jpg, jpeg, etc., But when I set the value of the element that holds HttpPostedFileBase to null it re triggers the change event and creates errors. is there any way to get around this?
I thought I could check at the beginning of the change event to see if the value is null but it doesn't work.
here is my html element (there are two because I'm hiding the upload text box and just displaying it as a button)
#Html.TextBoxFor(model => model.StudentImageFileBase, new { #type = "file", id = "selectedFile", style = "display: none;" })
<input type="button" value="Browse For Image" class="btn" id="pictureupload"/>
here is my javascript that checks the image type.
$(function () {
console.log("ready!");
alert("picture input function entered");
$("#pictureupload").click(function() {
document.getElementById('selectedFile').click();
});
$("#selectedFile").change(function() {
//this doesn't work
var imgVal = $('selectedFile').val();
if (imgVal == '')
return false;
//check whether browser fully supports all File API
if (window.File && window.FileReader && window.FileList && window.Blob) {
//get the file size and file type from file input field
var fsize = $('#selectedFile')[0].files[0].size;
var ftype = $('#selectedFile')[0].files[0].type;
var fname = $('#selectedFile')[0].files[0].name;
switch (ftype) {
case 'image/png':
case 'image/gif':
case 'image/jpeg':
case 'image/pjpeg':
alert("Acceptable image file!");
break;
default:
alert('Unsupported File!');
$('#selectedFile').val(null); //here is where the onchange gets triggered again and
return false;
}
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("selectedFile").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadPreview").src = oFREvent.target.result;
};
} else {
alert("Please upgrade your browser, because your current browser lacks some new features we need!");
return false;
}
});
});

So I think I figured it out!
I added the line below if the file is not a jpg/gif/etc
default:
alert('Unsupported File!');
$("#selectedFile").replaceWith($("#selectedFile").clone(true));
return false;
And it clears the httppostedfilebase memeber, so when I do a post back to my server the value is null. Maybe this isn't a good solution but it's all I have found so far. Just clearing out the element by setting its value re-triggers the change event which is what I am trying to avoid. Unless there is some simple logic I could put into the change event that would combat against it?

Related

How to detect a file input has been cleared programaticaly

I have file input that is added by a third party plugin, the uploaded file has a custom preview, which i can click on a remove button within the preview element to clear the input, and this preview is injected to the Dom uppon file addition. when i try to detect the action of clearing the input , neither change nor ìnput events are triggered.
Please note that i could normally listen to the change if file has been added only.
I have tried this:
const fileInput = document.getElementById('thumb');
fileInput.addEventListener('input', (e) => {
if( fileInput.files.length > 0 )
{
const file = fileInput.files[0]; // Get the first selected file
const blobURL = URL.createObjectURL(file);
}else{
console.log('removed');
}
});
And sure i tried to replace input with change but no result
Since you are having problems addressing the remove button and listen for its click event, and since a regular MutationObserver would be listening to the change of an attribute and not strictly an object's property value being changed,
you may try redefining the setter for the value property so that every time it will be changed programmatically, it will also perform your code.
You will find further details here (among the posted answers):
Detect input value change with MutationObserver
Here in this demo there's both the change event listener and the new property setter defined. When you'll try to clear the input using the corresponding button, the attempt to change its value property will be intercepted printing the value was changed programmatically! on console:
//adds a canonic change event handler to the #thumb element
document.getElementById('thumb')
.addEventListener('change',()=>{
console.log('file input has changed!');
});
//clear the input file programmatically (when the corresponding button is pressed)
function clearFile(){
document.getElementById('thumb').value = "";
}
//on document ready
document.addEventListener('DOMContentLoaded',()=>{
//overrides the setter for the value property of the #thumb element
const fileInput = document.getElementById('thumb');
const originalSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set;
Object.defineProperty(document.getElementById('thumb'), "value", {
set: function (newValue) {
//so that it will print on console..
console.log('the value was changed programmatically!');
//and perform its original designation
return originalSetter.call(this, newValue);
}
});
});
<input type="file" id="thumb">
<button onclick="clearFile();">CLEAR PROGRAMMATICALLY</button>
The solution I'm thinking of is to detect changes in the value of the input file by using a Javascript setInterval every 1 ms.
let fileInput = document.getElementById('thumb');
let check = document.getElementById('check');
let clear = document.getElementById('clear');
let currentValue;
let lastValue = '';
setInterval(()=>{
currentValue = fileInput.value;
if (lastValue !== currentValue && currentValue === '') {
console.log('interval: file removed');
} else if (lastValue !== currentValue && currentValue !== '') {
console.log('interval: file added');
}
lastValue = currentValue;
},1);
check.onclick = () => {
if(fileInput.files.length > 0) {
const file = fileInput.files[0]; // Get the first selected file
const blobURL = URL.createObjectURL(file);
console.log(blobURL);
console.log('onclick: file is exist');
} else {
console.log('onclick: file is empty');
}
}
clear.onclick = () => {
fileInput.value = '';
}
<input type="file" id="thumb">
<button id="check">Check</button>
<button id="clear">Clear</button>

HTML Input tag, with type file, in some cases doesn't catch "oninput " event

So, in my file upload page, I have a file dragging and dropping area. By clicking on this area, the file input dialog appears to allow the user to select files. In some random cases after selecting the files and clicked Open, the oninput event is not emitted. Am I doing something wrong?
I tried to change the oninput event to onchange. And it's not working to. Has anyone had this problem? Thanks in advance.
let input = document.createElement("input");
input.type = "file";
input.style.cssText = "display:none;";
input.multiple = true;
input.accept = "." + this.options.allowedFileType;
input.oninput = () => {
Array.from(input.files).forEach(file => {
if (file.type === "application/pdf") {
self.setUniqueUuidAndStoreFile(file);
} else {
self.displayErrorNotification(
this.$t("file") + " " + file.name + " " + this.$t("wrongFileType")
);
}
});
};
input.ondrop = function (event) {
return false;
};
input.click();
This is "normal" system doesnt register the change from time to time, because it doesnt see the whole file, for security reasons. The workaround we are using is seting the value on click to null
input.onclick = function () {
this.value = null;
};

How to validate file size from clientside using javascript in IE 7/8?

Currently I am using
if(navigator.appName=='Microsoft Internet Explorer'){
if(component.value){
var oas = new ActiveXObject("Scripting.FileSystemObject");
var e = oas.getFile(component.value);
var size = e.size;
}
}
to validate the file size.
Is there any other way to validate the size
Automation server can't create object error is displayed
I know it has something to do with Enabling ActiveX Controls in Settings, but thats not going to happen because one cant control client side system and IE7/8 doesnot even support file Api
IE doesn't support this feature
I had found a great plugin for file upload jQuery-File-Upload
Only IE 9 is not Supporting this Feature.
All Other IE Versions >9 have no Issues.
You can Resolve your issue By applying filter for IE 9 and get file size.
use Below code in else condition for other browsers as per Below.
if (browserInfo.indexOf("msie") > -1)
{
/* IE */
var filepath = document.getElementById('idControl').value;
if(browserInfo.indexOf("msie 9") == -1)
{
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
if (filepath == "") {
alert("Please Select File");
$("#selectorID").attr("src", $("#Contenturlprifix").val() + "/content/img/NoPhoto.png");
return false;
}
file = myFSO.getFile(filepath);
filetype = document.getElementById('idControl').accept
}
} else {
/* Other */
file = document.getElementById('idControl').files[0];
if (file == undefined) {
alert("Please Select File");
return false;
}
else {
filetype = file.type;
}
}
if (file != undefined) {
//10mb size
if (file.size / 1024 > 10240) {
alert("size Exists");
return false;
}
else if (filetype.indexOf('image/') == -1) {
alert("Select only images");
return false;
}
}
TRY THIS............
Go to internet options.
Select security tab.
Under Custom level.
Ensure that "Initialize and script active x controls is not marked safe for scripting" select the radio button enabled and try to run your code now, I am sure your problem will be solved.

Javascript, after disabling a button, need to make it available again. JS not working

Language: Javascript (PHP page)
I have 2 buttons on a page:
-- One is an upload image button (#upload),
-- & another is a "save / submit form" button (.multi-accordion-submit).
What the .js below does is it disables the submit button (.multi-accordion-submit) while files are being uploaded while user uses the other button (#upload) & text inside #upload says "Uploading...".
After an upload & text goes back to "Upload More" for #upload, the .multi-accordion-submit button's disabled attribute should now be removed.
But the problem is, it remains disabled and unclickable, rendering the submit button (.multi-accordion-submit) useless.
I don't know how to fix it, the code below looks fine & should work.
Any guidance and assistance would be greatly appreciated! Thanks for your time.
$(function () {
var btnUpload = $('#upload');
var status = $('#status');
var url = $('#upload_path').val();
new AjaxUpload(btnUpload, {
action: url,
//Name of the file input box
name: 'image',
onSubmit: function (file, ext) {
$('#upload-error').hide();
if (!(ext && /^(pdf|ai|psd|bmp|cdr|clk|gif|jpg|jpeg|ppt|pub|doc|docx|pcx|pic|pict|pct|png|ps|tif|tiff|emf|wmf|indd)$/.test(ext))) {
// check for valid file extension
$('#upload-error').show();
return false;
}
btnUpload.text('Uploading...');
$('.multi-accordion-submit').attr('disabled', true);
},
onComplete: function (file, response) {
if ($('.file-elements').length > 0) {
if ($('.file-elements:visible').length == 0) {
window.location.href = document.location.href;
} else {
btnUpload.text('Upload More');
$('.multi-accordion-submit').attr('disabled', false);
}
} else {
btnUpload.text('Upload More');
$('.multi-accordion-submit').attr('disabled', false);
}
//Add uploaded file to list
if (response === "success") {
$('<li></li>').appendTo('#files').html(file).addClass('upload-files');
} else {
$('<li></li>').appendTo('#files').text(file).addClass('upload-files');
}
}
});
});
//try to use
$('.multi-accordion-submit').attr('disabled','disabled');
//and
$('.multi-accordion-submit').removeAttr('disabled');
Attribute disabled is either exists or not (it`s value doesn't taken into account)
To remove disabled state from element you need to remove disabled attribute not just change it's value.
$('.multi-accordion-submit').removeAttr('disabled');
Notes:
Actually it may be confusing with jQuery because in 1.6+ prop and removeProp methods was introduced for work with native properties, but to remove disabled state you need to use prop and not removeProp (once removed native properties cannot be added again)
$('.multi-accordion-submit').prop('disabled', false);

How to Listen for Upload Finished with jQuery in WordPress Thickbox Upload Window?

I'm injecting some jQuery to make the Alt Text field required in WordPress upload thick box.
It intercepts the Insert into Post button click and checks if the field has been filled or not.
It works ok for the Gallery and Media Library tabs, but the From Computer tab needs a needs a "listener" when an upload finishes to alter the behavior of the Insert into Post button.
I was trying with setInterval, but don't know how to kill or recreate it, but maybe someone is aware if a listener exists, or even how to make this code work because I suspect my logic here is fuzzy...
Here's the code, commented.
add_action('admin_head-media-upload-popup','so_11149675_required_alt_text');
function so_11149675_required_alt_text()
{
// Detect current tab ("From Computer" == "type")
$tab = isset($_GET['tab']) ? $_GET['tab'] : "type";
// ( 'From Computer' or ( 'Gallery' and 'Library' ) )
$jquery = ('type' == $tab) ? 'var refreshUpload = setInterval(function(){$(".savesend input").each(checkAltTextPermanent);},500);' : '$(".savesend input").each(checkAltTextOnce);';
echo <<<HTML
<script language="javascript" type="text/javascript">
// var refreshUpload; /* testing */
// Function called by From Computer tab
// should run only once -> when the upload table and fields are created
function checkAltTextPermanent() {
// Create the required asterisk symbol
// setInterval creates a loop here
jQuery('.image_alt th label').each(function(i,e) {
jQuery('<span class="alignright"><abbr title="required" class="required">*</abbr></span>').prependTo(this);
});
// Alter button behavior
// Another loop in the alert box
jQuery(this).click(function(e) {
// clearInterval(refreshUpload);
var value = jQuery(this).parent().parent().parent().find('.image_alt input').val();
if('' != value)
return true;
alert ('Please fill the Alt text');
return false;
});
}
// Function called by Gallery and Library tabs
function checkAltTextOnce() {
jQuery(this).click(function(e) {
var value = jQuery(this).parent().parent().parent().find('.image_alt input').val();
if('' != value)
return true;
alert ('Please fill the Alt text');
return false;
});
}
jQuery(document).ready(function($) {
// Defined in PHP, calls checkAltTextOnce or checkAltTextPermanent
{$jquery}
// Used in Gallery and Libray tabs
$('.image_alt th label').each(function(i,e) {
$('<span class="alignright"><abbr title="required" class="required">*</abbr></span>').prependTo(this);
});
});
</script>
HTML;
}
Try this:
jQuery(".savesend input").live("click", validateAltText);
function validateAltText() {
var value = $(".image_alt input").val();
if (value)
return true;
alert('Please fill the Alt text');
return false;
}

Categories