9

here is my script. What I am trying to do is to trigger it using onchange event. But it seems does not work very well. I have tried edit here and there but still facing problems. As for my latest edit below, the problem is, there is 2 files to be uploaded, but only the second one will display alert message, while the first one will just receive any file.

    <script>
    function checkFile()
    {   
    var node_list = document.getElementsByTagName('input');
    for (var i = 0; i < node_list.length; i++) 
    {
        var node = node_list[i];
        if (node.getAttribute('type') == 'file') 
        {
            var sFileName = node.value;
            var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1];
            var iFileSize = node.files[0].size;
            var iConvert=(node.files[0].size/10485760).toFixed(2);
        }


        if (sFileExtension != "pdf" && sFileExtension != "doc" && sFileExtension != "docx" && iFileSize>10485760)
        {   
            txt="File type : "+ sFileExtension+"\n\n";
            txt+="Size: " + iConvert + " MB \n\n";
            txt+="Please make sure your file is in pdf or doc format and less than 10 MB.\n\n";
            alert(txt);
        }
    }
}
    </script>

my form,

  <input type="file" name="file" id="confirm" onchange="checkFile()">
  <input type="file" name="file" id="approveletter" onchange="checkFile()">
nanie
  • 109
  • 1
  • 2
  • 10

8 Answers8

23

Rather than relying on the elements them self you should use the given event to the function to get the file(s) that triggered the call to the callback function.

Passing in the event will guarantee you that you are actually working with the current files that caused the function to be called.

For example (I changed the variable name to make it more clear):

ONLINE DEMO HERE

/// pass in event 
function checkFile(e) {

    /// get list of files
    var file_list = e.target.files;

    /// go through the list of files
    for (var i = 0, file; file = file_list[i]; i++) {

        var sFileName = file.name;
        var sFileExtension = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
        var iFileSize = file.size;
        var iConvert = (file.size / 1048576).toFixed(2);

        /// OR together the accepted extensions and NOT it. Then OR the size cond.
        /// It's easier to see this way, but just a suggestion - no requirement.
        if (!(sFileExtension === "pdf" ||
              sFileExtension === "doc" ||
              sFileExtension === "docx") || iFileSize > 10485760) { /// 10 mb
            txt = "File type : " + sFileExtension + "\n\n";
            txt += "Size: " + iConvert + " MB \n\n";
            txt += "Please make sure your file is in pdf or doc format and less than 10 MB.\n\n";
            alert(txt);
        }
    }
}
  • Thanks @Ken I've followed the changes that u suggested above here but it does not respond anything. I also have tried the online demo you post, its working! I notice you put the getElementid above the function. I tried paste it to above my function, still not working. :( Help me please. – nanie Sep 23 '13 at 08:06
  • @nanie where you put the event listener shouldn't matter as functions are parsed before any execution takes place. Do you get any error messages in console? (ctrl + i in Chrome, ctrl + k in FF) –  Sep 23 '13 at 08:13
  • @nanie hard to tell without seeing the full code. Can you put your full code in a fiddle ? that makes it easier to detect possible other problems that can prevent this from running (as my example is working on its own). –  Sep 23 '13 at 08:27
  • I've update @Ken. Here, http://jsfiddle.net/TsxzR/2/ Please check it for me. If possible, guide me on handling the file as well. Thank you. Sorry for disturbing u at this hour. – nanie Sep 23 '13 at 08:36
  • @nanie I found an error in your loop, seem to work when that is fixed (http://jsfiddle.net/AbdiasSoftware/TsxzR/4/). You had a semi-colon instead of a comma (`for (var i = 0, file`). –  Sep 23 '13 at 20:32
  • Yes it work well in the fiddle. But after copied it to my code, it does not work anymore. :( – nanie Sep 24 '13 at 02:53
  • @nanie in your html file, do you specify doctype in the top of the file? if not try to specify it by adding this line: ` `. If not this work we need to do a deeper analysis. –  Sep 24 '13 at 02:57
  • I have it. Its there by default when I created the page. – nanie Sep 24 '13 at 03:17
  • my problem solved @Ken. I received help from others. Btw, thanks for helping me. For others, please try those code. Myb it will work with you and not me. – nanie Sep 24 '13 at 04:22
1

This might help

var file = document.getElementById("filex").files[0];
var filename = file.name;

var extSplit = filename.split('.');
var extReverse = extSplit.reverse();
var ext = extReverse[0];

if(!ext === "mp4" || !ext === "flv"){
  alert('Accepted');
} else {
  alert('Not accepted');
}
Lucky
  • 16,787
  • 19
  • 117
  • 151
Prodigy
  • 380
  • 3
  • 9
1

you can used this code with file controller in html. any only pass parameter and see the output

   <script type="text/javascript">
function AlertFilesize(cid,sz,a){
    var controllerID = cid;
    var fileSize = sz;
    var extation = a;
    if(window.ActiveXObject){
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        var filepath = document.getElementById('fileInput').value;
        var thefile = fso.getFile(filepath);
        var sizeinbytes = thefile.size;
    }else{
        var sizeinbytes = document.getElementById('fileInput').files[0].size;
    }
    var fSExt = new Array('Bytes', 'KB', 'MB', 'GB');
    fSize = sizeinbytes; i=0;while(fSize>900){fSize/=1024;i++;}
    var fup = document.getElementById('fileInput');
    var fileName = fup.value;
    var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
    if(ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG")
    {   
        var fs = Math.round(fSize);
        if(fs < fileSize && fSExt[i] == extation)
        {
            alert("Image Successfully Uploaded");
            return true;}else{
            alert("Please enter the image size less then"+fileSize+extation);
            document.getElementById('fileInput').value='';
            return false;
            }
        }else{
        alert("Must be jpg and gif images ONLY");
        document.getElementById('fileInput').value='';
        return false;}
    }
</script>
<input id="fileInput" type="file" onchange="AlertFilesize(this.id,100,'KB');" />
1
<script type="text/javascript">
function setFileSize() {
        var fileEl = document.getElementById('<%=FileUpload1.ClientID%>');
        var fileSize = fileEl.files[0].size / 1024 / 1024;
        var fileName = fileEl.files[0].name;
        var dotPosition = fileName.lastIndexOf(".");
        var fileExt = fileName.substring(dotPosition);
        if (fileSize > 1) {
        fileEl.value = '';
            document.getElementById('<%=lblFileStatus.ClientID%>').innerHTML = 'File Should Be less Than 1MB';
            return false;
        }
}


0

http://jsfiddle.net/kVdT5/

take a look at this fiddle. It is working perfact. as i said there is change in your if condition.

if (sFileExtension != "pdf" && sFileExtension != "doc" && sFileExtension != "docx" && iFileSize>10485760)

replace it with this

if ((sFileExtension != "pdf" && sFileExtension != "doc" && sFileExtension != "docx") || iFileSize>10485760))
Ronak Patel
  • 2,570
  • 17
  • 20
  • Thanks but I don't really get you explanation. As I said earlier, it works well for the second file i'm trying to upload. It give me error if the file is other that stated or in bigger size and do nothing if it is in acceptable extension and size. But act differently towards the first file. I'm guessing the problem comes from for loop but I don't know how to solve. – nanie Sep 19 '13 at 08:55
  • I think there is problem with your if statement. see my updated answer – Ronak Patel Sep 19 '13 at 09:04
  • No different @Patel .. Still the same. I try upload the same file for both but only the second one respond to the condition. – nanie Sep 20 '13 at 01:47
  • The if statement of the original code will not alert anything in case of a pdf or a doc bigger than 10 MB. The alert will be shown only in case of a file bigger than 10 MB and (&&) not pdf nor doc, which is not what you want. – MPavesi Sep 20 '13 at 06:46
0
    <!DOCTYPE html>
        <html>
        <body>

        <p>When you submit the form, a function is triggered which alerts some text.</p>

        <form action="demo_form.asp" id="form">
          Enter name: <input type="file" name="fname" id="form_file" onchange=" return myFunction()">
          <input type="submit" value="Submit" id="submit">
        </form>

        <script>
        function myFunction() {
             var file = document.getElementById("form_file");
             var file_name = file.value;
             var extension = file_name.split('.').pop().toLowerCase();
             var size      = file.files[0].size;
             var allowedFormats = ["jpeg", "jpg", "pdf", "tif"];

              if(!(allowedFormats.indexOf(extension) > -1)){
               alert("Enter a jpg/jpeg/pdf/tif file");

               document.getElementById("submit").disabled = true;
               return false;              
              } else if( ((size/1024)/1024) > 15){
                 alert("Your file should be less than 15MB");
                 return false;
              } else {
               document.getElementById("submit").disabled = false;   
              }
        }
        </script>
        </body>
        </html>
0

This is JavaScript onchange event base file size and type validation script, and it can be use in multiple input files

<input type="file" onchange="checkFile(this)" class="form-control" name="doc_file[]">
<script>
function checkFile(item){
    var extension = $(item).val().split('.').pop().toLowerCase();
// Create array with the files extensions that we wish to upload
    var validExtensions = ['jpeg', 'jpg', 'cdr', 'pdf', 'tiff'];
    //Check file extension in the array.if -1 that means the file extension is not in the list.
    if ($.inArray(extension, validExtensions) == -1) {
        $('#errormsg').text("Failed! Please upload jpg, jpeg, cdr, tiff, pdf file only.").show();
    // Clear fileuload control selected file
        $(item).replaceWith($(item).val('').clone(true));
    //Disable Submit Button
        $('#submit').prop('disabled', true);
    }
    else {
    // Check and restrict the file size to 32 KB.
        if ($(item).get(0).files[0].size > (20971520)) {
            $('#errormsg').text("Failed!! Max allowed file size is 20 MB").show();
        // Clear fileuload control selected file
            $(item).replaceWith($(item).val('').clone(true));
        //Disable Submit Button
            $('#submit').prop('disabled', true);
        }
        else {
        //Clear and Hide message span
            $('#errormsg').text('').hide();
        //Enable Submit Button
            $('#submit').prop('disabled', false);
        }
    }
};
</script>
-1

Here is my solution

function checkFile(field){
    let imagePath = field.value;
    let allowedExtensions = /(\.jpg|\.png|\.jpeg|\.JPG|\.PNG|\.JPEG|\.jPg|\.pNg|\.jPeg|\.jpG|\.pnG|\.jpEg|\.JPg|\.PNg|\.JPeg)$/i;
    if (field.files[0].size > (2 * 1048576)){ // 2 MB
        // size exceeds
    }else if (!allowedExtensions.exec(imagePath)) {
        // extensions does not match
    } else {
        // everything OK
    }
}
hassanrazadev
  • 626
  • 9
  • 15