I have a ASP website page where i have a upload control added
<asp:FileUpload ID="FileUpload1" runat="server"
BorderStyle="None" Width="215px" onchange="return checkfile();" style="margin-left: 14px" BackColor="#F0F0F0" />
From javascript i am validating the file which will be uploaded. If it is of type .exe then I will not allow to upload and give a message. if not i will display the file name in label "lblFileName" . But the problem if error(in case file is exe) then i want to reset the upload control(FileUpload1) . Now it will show only message but allows form to submit along with the .exe file.So how I can reset it?
function checkfile() {
var filename = document.getElementById("FileUpload1").value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
var FileExt = filename.split('.').pop();
if (FileExt == "exe") {
document.getElementById('<%=lblFileName.ClientID%>').innerHTML = "you cannot attach exe file";
return false;
}
else {
document.getElementById('<%=lblFileName.ClientID%>').innerHTML = filename;
}
}
Your code is the problem onchange="return checkfile();"
And your function should look like
function checkfile() {
var filename = document.getElementById("FileUpload1").value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
var FileExt = filename.split('.').pop();
if (FileExt == "exe") {
document.getElementById('lblFileName').innerHTML = "you cannot attach exe file";
document.getElementById("FileUpload1").value='';
return false;
}
else {
document.getElementById('lblFileName').innerHTML = filename;
}
}
Return will disallow file to put in your file upload control so this will solve your problem
Please check demo here
I am doing it this way using jquery:
$(function () {
$('<%= fileUploadCV.ClientID %>').change(function () {
//because this is single file upload I use only first index
var f = this.files[0]
//here I check if the file size is bigger than 8 MB (numbers below are in bytes)
if (f.size > 8388608 || f.fileSize > 8388608)
{
//show an alert to the user
alert("Allowed file size exceeded. (Max. 8 MB)")
//and RESET file upload control
this.value = null;
}
})
});
Related
When i upload multiple images and one of them which is not valid extension and message should be shown File type is not valid and when I upload images one by one it works perfect please help me how can resolve that ? thank u
javascript
$("input[type=file]").on('change', function(){
//Get uploaded file extension
var extension = $(this).val().split('.').pop().toLowerCase();
// Create array with the files extensions that we wish to upload
var validFileExtensions = ['jpeg', 'jpg', 'png'];
//Check file extension in the array.if -1 that means the file extension is not in the list.
if ($.inArray(extension, validFileExtensions) == -1) {
$('#filetype').text("File type is not valid").show();
$('#btnSubmit').prop('disabled', true);
}
});
With the multiple attribute added to the input HTML tag, iterate the files property on the input element in the change event listener.
document.addEventListener('DOMContentLoaded', function () {
document.querySelector("input").addEventListener("change", changeHandler);
});
function changeHandler() {
const validFileExtensions = ['jpeg', 'jpg', 'png'];
// 'this' refers to the 'input' HTML element
// Assigning 'this' to the 'element' variable is not
// necessary but assigned here for code readability.
let element = this;
// Check if the element has a FileList before checking each file
if (element.files && element.files.length) {
for (i = 0; i < element.files.length; i++) {
const file = element.files[i];
const filename = file.name;
const extension = filename.split('.').pop();
if (validFileExtensions.includes(extension)) {
console.log("VALID file -> " + filename);
}
else {
console.log("INVALID file -> " + filename);
}
}
}
}
<input type="file" multiple />
Applying the code above to your jQuery code:
$("input[type=file]").on('change', function() {
//Get uploaded file extension
var extension = $(this).val().split('.').pop().toLowerCase();
// Create array with the files extensions that we wish to upload
var validFileExtensions = ['jpeg', 'jpg', 'png'];
//Check file extension in the array.if -1 that means the file extension is not in the list.
if ($.inArray(extension, validFileExtensions) == -1) {
$('#filetype').text("File type is not valid").show();
$('#btnSubmit').prop('disabled', true);
}
// Check if the element has a FileList before checking each file
if (this.files && this.files.length) {
var message = "";
for (i = 0; i < this.files.length; i++) {
var file = this.files[i];
var filename = file.name;
var extension = filename.split('.').pop();
if (!validFileExtensions.includes(extension)) {
message += filename + " is not a valid file type. ";
}
}
if (message !== "") {
$('#filetype').text(message).show();
$('#btnSubmit').prop('disabled', true);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="fileInput" multiple>
<span id="filetype"></span>
<button type="submit">Upload</button>
const fileInput = document.querySelector('input[type="file"]');
const submitBtn = document.querySelector('button[type="submit"]');
submitBtn.disabled = true;
fileInput.addEventListener('change', () => {
const fileName = fileInput.value;
const fileType = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
if (fileType !== 'jpg' && fileType !== 'jpeg' && fileType !== 'png' && fileType !== 'gif') {
alert('File is not an image');
fileInput.value = '';
submitBtn.disabled = true; // Disable the submit button
} else {
submitBtn.disabled = false; // Enable the submit button
}
});
.fileInput{
text-align:center;
margin-top:10%;
}
<div class="fileInput">
<input type="file" id="fileInput">
<button type="submit">Upload</button>
</div>
I'm doing some web development using Django. There comes a part where user could upload images to my server.
Here is the Javascript side of the code.
var uploadField = document.getElementById("file_upload");
uploadField.onchange = function(){
var file_type=this.file[0]['type']; // file_type = 'image/jpg'
if (file_type.split('/')[0] !== 'image'){
alert("Not an Image");
this.value = "";
}
else if(this.files[0].size > 2097152){
alert("File is too big!");
this.value = "";
}
else{
this.form.submit();
document.getElementById('celimsg').innerHTML='Analyzing image...';
document.getElementById('celi').src=gif_url;
}
}
It didn't work. When the files are uploaded, nothing happens. But if I remove the validation part:
var uploadField = document.getElementById("file_upload");
uploadField.onchange = function(){
if(this.files[0].size > 2097152){
alert("File is too big!");
this.value = "";
}
else{
this.form.submit();
document.getElementById('celimsg').innerHTML='Analyzing image...';
document.getElementById('celi').src=gif_url;
}
}
It started working again.
Unlike other web development platform, Django doesn't support debugging for javascript and I can't put print statements on it etiher.
Looks like I spelled 'files' incorrectly.
var uploadField = document.getElementById("file_upload");
uploadField.onchange = function(){
var file_type=this.files[0]['type'];
if (file_type.split('/')[0] !== 'image'){
alert("Not an Image");
this.value = "";
}
else if(this.files[0].size > 2097152){
alert("File is too big! Keep it under 2MB.");
this.value = "";
}
else{
this.form.submit();
document.getElementById('celimsg').innerHTML='Analyzing image...';
document.getElementById('celi').src=gif_url;
}
}
Cheers!
Any sample codes guys about the uploading a PDF file only that validates the size not more than 2mb. If the file is more than 2mb the system will not accept the file or just delete the file on the form so the user will upload again the right file(less than or equal to 2mb). Thank you so much guys. and sorry for my bad english.
You may try this JavaScript code with your html file.
function SubmitForm() {
var imgpath = document.getElementById("fileUpload").value;
if(imgpath=="")
{
document.getElementById("lblError").innerHTML = "No file was chosen before clicking on Upload button. Please chose a file first.";
return;
}
var allowedFiles = [".pdf"];
var fileUpload = document.getElementById("fileUpload");
var lblError = document.getElementById("lblError");
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
if (!regex.test(fileUpload.value.toLowerCase())) {
lblError.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.";
return;
}
if (fileUpload.files[0].size > 2097152){
lblError.innerHTML = "File size is more than 2 MB.";
return;
}
lblError.innerHTML = "";
return;
lblError.innerHTML = "File Upload in Progress.......";
document.form.action = "upload_filedata.asp";
document.form.submit();
}
And Call this "JavaScript:SubmitForm();" with you Submit button.
I trying to display the name of the file after the user has uploaded it. The file uploads successfully but in the javascript it keeps displaying the message below:
The file (undefined) was uploaded successfully!
It keeps displaying undefined when it should display the filename. Why is this? At the moment what is happening is that wen the user uploads the file, the files is uploaded into the "ImageFiles" folder, when uploading is finsihed the javascript function below displays the message to state the name of the file which has been successfully uploaded.
Below is the code which displays the file name and message after uploading:
function stopImageUpload(success){
function handleFileSelect(evt) {
var files = evt.target.files;
localStorage["fname"] = files[0].name; //save the name for future use
}
$('.fileImage').bind('change', handleFileSelect, false);
var result = '';
if (success == 1){
result = '<span class="msg">The file ('+localStorage["fname"]+') was uploaded successfully!</span><br/><br/>';
localStorage["fname"] = undefined; //remove the temporary variable
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
Below is form:
<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='stopImageUpload(this);' class='imageuploadform' >
<p>Image File: <input name='fileImage' type='file' class='fileImage' />
<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' />
</p>
</form>
Try this:
var fileName;
function stopImageUpload(success){
function handleFileSelect(evt) {
var files = evt.target.files;
fileName = files[0].name; //save the name for future use
}
$('.fileImage').bind('change', handleFileSelect, false);
var result = '';
if (success == 1){
result = '<span class="msg">The file ('+fileName+') was uploaded successfully!</span><br/><br/>';
fileName = ""; //remove the temporary variable
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
Not tested, but try using getItem/setItem and see if that changes anything!
function stopImageUpload(success){
function handleFileSelect(evt) {
var files = evt.target.files;
console.log(files[0].name); //see if a name really exists, or if something is wrong outside this function?
localStorage.setItem("fname", files[0].name); //save the name for future use
}
$('.fileImage').on('change', handleFileSelect);
var result = '';
if (success == 1){
result = '<span class="msg">The file ('+localStorage.getItem("fname")+') was uploaded successfully!</span><br/><br/>';
localStorage.setItem("fname", ""); //remove the temporary variable
} else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
I have a question regarding to JavaScript validation. I am validaing the <input type="file"> whenever my scripts runs, it validates but also the action page is called. I want to stop the action page until the validation is complete. Here is my code, any help will be awesome. Regards
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Image Uploading</title>
</head>
<body>
<form name="xx" action="server.php" method="post" enctype="multipart/form-data" onsubmit="Checkfiles(this)">
<input type="file" name="file_uploading" id="filename">
<input type="submit" value="Submit" name="uploadfile">
</form>
<form name="view" method="post">
View your uploaded Images
</form>
</body>
</html>
<script type="text/javascript">
function Checkfiles() {
var fup = document.getElementById('filename');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext =="GIF" || ext=="gif") {
return true;
} else {
alert("Upload Gif Images only");
return false;
}
}
</script>
var fname = "the file name here.ext";
var re = /(\.jpg|\.jpeg|\.bmp|\.gif|\.png)$/i;
if (!re.exec(fname)) {
alert("File extension not supported!");
}
File Extension Validation through javascript
function ValidateExtension() {
var allowedFiles = [".doc", ".docx", ".pdf"];
var fileUpload = document.getElementById("fileUpload");
var lblError = document.getElementById("lblError");
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
if (!regex.test(fileUpload.value.toLowerCase())) {
lblError.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.";
return false;
}
lblError.innerHTML = "";
return true;
}
onclick event of submit button call this javascript function.
With the help of ID = lblError , print the error message in html section.
You can use the File Api to test for magic number. Maybe take a look at this answer for other ideas about the validation. More reliable than the file extension check.
The return value of the submit handler affects the submission.
onsubmit="return Checkfiles();"
This is basically saying:
form.onsubmit = function () { return Checkfiles(); };
In general, you can use JavaScript some() method for that.
function isImage(icon) {
const ext = ['.jpg', '.jpeg', '.bmp', '.gif', '.png', '.svg'];
return ext.some(el => icon.endsWith(el));
}
const fname = "filename.ext";
if (!isImage(fname)) {
console.log("File extension not supported!");
}
You need to return CheckFiles()
Upload bulk data through excel sheet(.csv)
$("form").submit(function(){
var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(csv)$");
if(!(regex.test(val))) {
$(this).val('');
alert('Only csv file can be uploaded');
return false;
}
});
var _URL = window.URL || window.webkitURL;
$("input[type=file]").change(function(e) {
var file;
if ((file = this.files[0])) {
var img = new Image();
img.onload = function () {
// do to on load
};
img.onerror = function () {
alert("valid format " + file.type);
};
img.src = _URL.createObjectURL(file);
}
});
The fileValidation() function contains the complete file type validation code. This JavaScript function needs to call for file extension validation.
HTML
<!-- File input field -->
<input type="file" id="file" onchange="return fileValidation()"/>
<!-- Image preview -->
<div id="imagePreview"></div>
JavaScript
function fileValidation(){
var fileInput = document.getElementById('file');
var filePath = fileInput.value;
var allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
if(!allowedExtensions.exec(filePath)){
alert('Please upload file having extensions .jpeg/.jpg/.png/.gif only.');
fileInput.value = '';
return false;
}else{
//Image preview
if (fileInput.files && fileInput.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('imagePreview').innerHTML = '<img src="'+e.target.result+'"/>';
};
reader.readAsDataURL(fileInput.files[0]);
}
}
}
fileValidation()
> html
<input type="file" id="userfile" name="userfile" value="" class="form-control userfile" required>
> javascript
$(document).on('change', '.userfile', function (e) {
e.preventDefault();
const thisValue = $(this).val().split('.').pop().toLowerCase();
const userFile = [thisValue];
// Allowing file type
const validFile = ['csv', 'xlsx'];
// const intersection = validFile.filter(element => userFile.includes(element));
// if(intersection == ''){
// $(this).val('');
// alert('Please Select ' + validFile + ' file');
// return false;
// }
// Allowing file type
const allowedExtensions = /(\.csv|\.xlsx)$/i;
if (!allowedExtensions.exec($(this).val())) {
$(this).val('');
alert('Please Select ' + validFile + ' file');
return false;
}
});