Limit the types of files users can upload
The following JavaScript function can be used to validate that the type of file that a user tries to upload is of a certain format. It does this by checking that the files extention (eg .html) is in an array of allowed extensions that is passed to the function as an argument.
<script type="text/JavaScript">
<!-- Begin
function TestFileType( fileName, fileTypes ) {
if (!fileName) return;
dots = fileName.split(".")
//get the part AFTER the LAST period.
fileType = "." + dots[dots.length-1];
return (fileTypes.join(".").indexOf(fileType) != -1) ?
alert('That file is OK!') :
alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
}
// -->
</script>
You can test it using the file upload below which will only accept image files that end in either .gif, .jpg or .png:
or, alternatively, you could put it in the onChange event of the file upload element.
Note that the above example assumes that you know the "name" attribute of the file upload element. In domino R5 you can do this to an upload by putting a name in its HTML attributes. In R4 you cannot do this so you can either create the upload yourself by using the following pass-thru html
<input type="file" name="uploadfile">
Otherwise you would need to loop through all elements on the form looking for any input of type "file" and then validating this. This method is demonstrated here.
Note: This is not entirely foolproof as people can easily change the extension of a file before uploading it, or do some other trickery, as in the case of the "LoveBug" virus.
FIle Upload
When I assign a name to the file upload the submit fails. My guess is that it has to do with a name on the web page that domino does not have listed - similiar to creating a field using html and not having a NOTES equivlant on the form.So, I tried creating a NOTES field with that same name and the form submitted by failed to attach the item. (The trick to create textarea fields)How does on get around this?
Reply
Re: FIle Upload
Good question, "how can i work with this when i use the default Domino file upload facility ?
If i look in the code Domino generates something like:
input type="file" name="%%File.c1256c850038f824.81a1da37dba5ee80c1256cda0039990c.$Body.0.2726"
Reply
Show the rest of this thread
Re: FIle Upload
Hi! Nice Script.
I have a Question How to verify if a file selected by user exsist on the user system using javascript.
Lets says user select's a file and the user has no rights to copy/execute/read permission to that file,or simply the user changes the exetension of the file in the textbox.
Then how to verify before saving the document using javascript.
Reply
Show the rest of this thread
Unable to check Gif files
Something that I discovered, it can't check the gif files.
Reply
Re: Unable to check Gif files
You're right Charlotte. My mistake ;o)
The line: return (fileTypes.join(".").indexOf(fileType) != -1)
Generates and test the following string for the existence of ".gif"
"gif.jpg.png.bmp"
Obviously the .join() is not addding a period at the beginning. I'll leave this to you to work out how...
Jake
Reply
Show the rest of this thread
failed in this case...
This particular script failed or rather incorrectly thought that the following file was bad: D:\Temp\folder.name.exe\somethingexe.txt
The path is admittedly ridiculous but as another site said 'God is always building a better idiot'.
Reply
Re: failed in this case...
Woops. Got to admit I never thought of catering for folders with .s in the name.
The thing to do here is explode on the "\"s before you explode on the "."s...
Jake
Reply
Is it possible to restrict no of attachment on web
Hi,
Is it possible to restrict no of attachments on web without using setting in server document.
RIshi
Reply
javascript file upload validation
I have a form which is uploading a file. I want to use javascript to validate the file by making sure it isn't to big (not exceeds more 50 chars) and that it is of proper file type(*.zip. Unfortunetly I have no idea of how to go about validating either of the two things I need validated.
I've searched using google for the answers and have found many pages of nothing or "sign up to find the solution" so any help would be greatly appreciated
Reply
Re: ASP file upload validation
Dear check it out it may help u.
Or u can use Reqular expression validator for the purpose
if (FileUpload1.HasFile) { string[] FileExt ={ ".exe", ".txt", ".dat", "EXE", "TXT" }; for (int i = 0; i < FileExt.Length; i++) { if (UpPath.Contains(FileExt[i])) { chk = false; }
} if (chk == false) { Filemsg.Text = "Invalid File Format"; } else { FileUpload1.SaveAs(UpPath); Filemsg.Text = "File Uploaded Succesfully"; FileName.InnerHtml = FileUpload1.PostedFile.FileName; FileType.InnerHtml = FileUpload1.PostedFile.ContentType; Size.InnerHtml = Convert.ToString(FileUpload1.PostedFile.ContentLength); FileDetail.Visible = true; } } else { Filemsg.Text = "Uploading Failed! Select some file to Upload"; FileDetail.Visible = false; } }
Reply
Re: javascript file upload validation
I want code to make validation in FileUpload to check the type of the file I want to upload and if there is file to upload or its empty
regards
Reply
Hide the rest of this thread
Re: javascript file upload validation
can u plz send me validations for file upload from frontend it only allow .xls file
Reply
Re: javascript file upload validation
how can i use validation i upload file
Reply
Re: javascript file upload validation
Sir , I want to validate a upload file field and want to check that it only allow to pdf file to upload.
Reply
Re: javascript file upload validation
Reply
Show the rest of this thread
Re: javascript file upload validation
asdf
Reply
Nice script
Hello !!!
thanks for this nice script !! :-)
Does some one know how to check also the file-size? (for example: to give an alert in the case the file is above a certain limit. )
Reply
check for non-web characters
Hi, another good idea is to check for "ugly" characters in the filename that prevent the attachment from being able to be opened. "Ugly" means non-english characters.
Just encode the filename (means: translate to unicode) and check if it is the same as the original. But don't care about spaces.
// replace a space with something harmless var file_nameC = file_name.replace(/ /g, "a"); if (encodeURIComponent(file_nameC) != file_nameC) error_feld = error_feld +'\n\t Characters found in filename not suitable for webaccess!';
Michael
Reply
not working
your function is not working on ur site
Reply
Re: not working
Woops. Fixed now. Thanks for letting me know.
Reply
Some bugs, fixed
function TestFileType( fileName, fileTypes ) {
if (!fileName) return;
dots = fileName.split(".");
//get the part AFTER the LAST period.
fileType = "." + dots[dots.length-1];
return ('.'+fileTypes.join(".").indexOf(fileType) != -1) ?
alert('That file is OK!') :
alert("Please only upload files that end in types: \n\n ." + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
Missing a semicolon at dots = fileName..., I know that's not a big deal, also included the initial '.' before the fileTypes.join and in the alert box for cosmetic purposes. Otherwise the first file type in the file array sometimes gets ignored.
Tangentially, if you want to be able to clear the file input box: IE won't let you change the value of an input type=file box directly, so you need to delete the input element and replace it with a fresh new element. If you want it to trigger automatically, bind it to the 'change' event, either by using the inline onchange='' attribute or using your event binding method of choice.
Reply
Oh, another thing
return ('.'+fileTypes.join(".").indexOf(fileType.toLowerCase()) != -1) ?
Replace as above, indexOf is case sensitive so this should help with that :)
Reply
Slight change to get this working
Hi All,
Great little function.
I had a small problem with this still submiting the form no matter what the outcome. I needed to 'return' the function for it to know that I'd stopped the form submit.
onClick="return TestFileType(this.form.uploadfile.value, ['gif', 'jpg', 'png', 'jpeg']);"
Reply
hello :),what happen if try to upload image with this name "test.ff.png" ?
You get a wrong result :)
Just get the lastIndexOf('.') then used the subString(), and then split into array :)
Reply
From the code above (which btw is almost 10 years old!):
dots = fileName.split(".")
//get the part AFTER the LAST period.
fileType = "." + dots[dots.length-1];
It already caters for multiple dots :)
Reply
Hello everyone... I did a few modifications for our site and thought I'd share it with you all. The only thing I just found out is IE doesn't fire off the check so I'm looking into that. If anybody knows why feel free to reply. :)
function TestFileType(fileName, fileTypes) {
var myReturn = false;
if (!fileName) return;
dots = fileName.split(".");
//get the part AFTER the LAST period.
fileType = dots[dots.length-1];
if (fileTypes.indexOf(fileType) != -1)
myReturn = true;
else{
alert("Please only upload files that end in types: \n\n" + (fileTypes.join(" .")) + "\n\nPlease select a new file and try again.");
document.getElementById('cf_file').value = '';
}
return myReturn;
}
cfinput/input attribute call: onChange="TestFileType(this.form.cv_file.value, ['doc', 'docx', 'pdf']);"
I chose to use onChange instead of onClick or onBlur. onChange checks it after making the selection. onClick wouldn't work in FF or IE and onBlur only worked after you left the field in FF (didn't work at all in IE)
I also chose to do the if else instead of the ? : simply because I couldn't get it to do what I wanted it to do (clearing the field after sending the alert) and as far as the message being okay I didn't need to send a file is ok alert. Nevertheless this has helped greatly, thank you everyone for your input and for the original code! We'll be using this more I'm sure. :) That way we can try and prevent everything having to be checked on the server side.
Reply
CODIGO FINAL
function checkTipoFileInput( fileNombre, fileTypes ) {
/*Ejemplo de uso desde un evento Click
* onClick="return checkTipoFileInput(this, ['gif', 'jpg', 'png', 'jpeg']);"
*/
// Existe este file input
if (fileNombre.value.length<3){
fileNombre.value='';
fileNombre.setAttribute('type', 'input');
fileNombre.setAttribute('type', 'file');
return false;
}
dots = fileNombre.value.split(".");
fileType = "." + dots[dots.length-1];
if(fileTypes.join(".").indexOf(fileType) != -1){
alert('OK, es un archivo permitido.');
return true;
}else{
alert("Por favor, sólo se pueden subir archivos de tipo: \n\n" + "."+(fileTypes.join(" .")) + "\n\nPor favor, seleccione un nuevo archivo y vuelva a intentarlo.");
fileNombre.value='';
fileNombre.setAttribute('type', 'input');
fileNombre.setAttribute('type', 'file');
return false;
}
}
SALUDOS ;-)
Reply
How do I validate the fileType by case insensitive?
Reply
Hello Jake Howlett,
Greetings!
I got your contact from notes.net.
I am the first time user of FileUpload Control. In my application, there is a master notes database, in which I added this new Fileupload control to a form. But the documents are actually saved in another sub-database via webQuerySave Agent. I chosen the file and then when I click save button, the webQuerysave agent gets triggered and while executing the below code snippet, of WebQuerySave Agent, v2FileNames(0) returns null value only. I am actually trying to get the object embedded and reattach it to the subdatabase document while saving it. But attachment is not returned. If you could reply with modified code snippet/approach/screenshots it would be greatly helpful. I am using LN 8.5.
v2FileNames = Evaluate("@AttachmentNames", doc)
messagebox "Filename - - > " & v2FileNames(0)
here doc is the Session documentcontext.
Thanks in Advance.
Sundar.
Reply