0

So I have this JS and it's working perfectly fine, but is it possible to change it from getElementById 'studentPhoto' into input type="file" instead?

Because I have many

<input type="file" id="studentPhoto">
<input type="file" id="studentPhoto">

Basically what I want to do is that the below JS will works in every studentPhotoId

  document.getElementById('studentPhoto').addEventListener('change', checkFile, false);

         function checkFile(e) {

             var file_list = e.target.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 / 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);
                 }
             }
         }

Thanks

Sarah
  • 329
  • 5
  • 21

2 Answers2

2

You could switch to a JQuery Selector. The below works on a project of mine with 2 file inputs.

function checkFile(e) {

    var file_list = e;

    for (var i = 0; i <= file_list.length; i++) {
       //Do stuff here
    }
}

$("input[type='file']").change(function () {
    checkFile(document.getElementById($(this).attr("id")).files);
});

Hope that helps

Wheels73
  • 2,850
  • 1
  • 11
  • 20
  • Just a question regarding MVC Core IFormFile, is there a way to add checking FileType or FileSize in the model? like [Required], [FileType] so in my server side the file won't be uploaded – Sarah Feb 01 '18 at 09:14
  • when you post the HttpPostedFileBase to your server, you should be able to check the ContentLength. Have a look at this link https://stackoverflow.com/questions/10445861/validating-for-large-files-upon-upload – Wheels73 Feb 01 '18 at 09:19
1

Change:

document.getElementById('studentPhoto')

To:

$("input['type=file']")

Also, you shouldn't use the same id on multiple elements, instead use class. To select an element by class:

<input type="file" class="studentPhoto"> <input type="file" class="studentPhoto">

$('.studentPhoto')

Barskey
  • 423
  • 2
  • 5
  • 18