2

I am working with input type file, if image selected it will show preview if other than image selected (pdf/docx)I want to show alert invalid,but getting error :Cannot read property 'split' of undefined

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>

<input type='file' id='input1'>
<div class="hide_this" style="display:none;">    <img id='imagepreview1' width="100" height="100" >
<button type="button" class="close" aria-label="Close" style="position: absolute;top:30px;opacity:1.2;">
  <span aria-hidden="true" style="color:black;">&times;</span>
</button>
</div>


<script>
$("#input1").change(function() {
    readURL(this);
    $('#imagepreview1').show();
    $('.hide_this').css({
        'display': 'block'
    });
});
$('.close').click(function() {
    $(".hide_this").hide();
    document.getElementById("input1").value = "";
    $("#imagepreview1").hide();
});

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            var ext = input.files[0].split('.').pop().toLowerCase();
            if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg']) == -1) {
                alert('invalid extension!');
            }
            $('#imagepreview1').prop('src', e.target.result).show();
        }
        reader.readAsDataURL(input.files[0]);
    }
}
</script>
4
  • where is your my_file_field input defined ? Commented Mar 30, 2019 at 2:16
  • Use ([^\\s]+(\\.(?i)(jpg|png|gif|bmp))$) that regex to check for a valid image extension. Because I could beat your check by just making a file named jpg.exe Commented Mar 30, 2019 at 2:24
  • Might also consider using an accept attribute stackoverflow.com/questions/181214/… Commented Mar 30, 2019 at 2:25
  • that would imply input.files[0] is undefined, which clearly it can't be! Commented Mar 30, 2019 at 2:27

3 Answers 3

1

In response to my comment and your request, besides the undefined error. You could beat your security check by just making a file named: jpg.exe.

Use a regex expression, and make sure your file is actually selected. Use the onselect event.

let good = 'test.jpg';
let bad = 'jpg.test';
let re = (/\.(gif|jpg|jpeg|tiff|png)$/i).test(good);
if (re) {
    console.log('Good', good);
}

console.log('Bad:', bad);

And make sure change to this

let ext = $("#input1").val().split(".").pop().toLowerCase();

For a PDF, you could use a library after evaluating the expression.

var url = 'https://s1.q4cdn.com/806093406/files/doc_downloads/test.pdf';


let re = (/\.(pdf)$/i).test(url);
if (re) {
  console.log(re);
  //
  // Asynchronous download PDF
  //
  var loadingTask = pdfjsLib.getDocument(url);
  loadingTask.promise.then(function(pdf) {
    //
    // Fetch the first page
    //
    pdf.getPage(1).then(function(page) {
      var scale = 1.5;
      var viewport = page.getViewport({
        scale: scale,
      });
      //
      // Prepare canvas using PDF page dimensions
      //
      var canvas = document.getElementById('the-canvas');
      var context = canvas.getContext('2d');
      canvas.height = viewport.height;
      canvas.width = viewport.width;
      //
      // Render PDF page into canvas context
      //
      var renderContext = {
        canvasContext: context,
        viewport: viewport,
      };
      page.render(renderContext);
    });
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.2.2/pdf.js"></script>
<canvas id="the-canvas" style="border:1px  solid black"></canvas>

Sign up to request clarification or add additional context in comments.

6 Comments

I messed the expression up, I am going to fix it. My bad, one sec I'll help. But that's the idea.
thanks for your help,last thing just now i got requirement if pdf/docx type file then use embed tag to show preview ,instead of showing alert currently I am developing project so I got requirement like this
Ok, give me a sec. I won't abandon you.
@Anonymous I gave you an example for a pdf, just use regexr.com to test your regex expression. And for Javascript regex, developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…
thank you so much for your help and valuable time to solve this issue
|
1

You're trying to read the value of an input with an ID of my_file_field which doesn't exist - use input1 instead:

var ext = $("#input1").val().split(".").pop().toLowerCase();

1 Comment

I want to show preview if file type is pdf or docx in html embed tag, how to do this
0

You file input is #input1 not #my_file_field

change

var ext = $('#my_file_field').val().split('.').pop().toLowerCase();

to

var ext = $('#input1').val().split('.').pop().toLowerCase();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.