Display an alert message through jQuery script if the input type file is not an image

When working with an input type file, if an image is selected it will show a preview. If something other than an image, like a PDF or DOCX file, is selected I want to show an alert as invalid. However, I am encountering an 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].name.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>

Answer №1

Upon reading your comment and request, in addition to the undefined error mentioned. One potential way to bypass your security check is by creating a file named: jpg.exe.

To achieve this, utilize a regex expression and ensure that your file is correctly selected. Utilize 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);

It's also important to make sure you implement this change:

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

In the case of a PDF file, consider using 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);
  //
  // Asynchronously 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>

Answer №2

If you're attempting to retrieve the value of an input element with the ID my_file_field and it doesn't exist, make sure you are using input1 instead:

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

Answer №3

Your selected file is labeled as #input1 instead of #my_file_field

Update

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

to

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sorting data on-the-fly using an HTML Select drop-down menu

Looking for a way to dynamically sort data from a JavaScript object based on the user's selected option. If the user chooses ID, the data should be sorted by ID, and the same goes for Name. I've created a function and attached an onchange method ...

Rendering an object as a React child is not allowed (object found with keys {this}). To display multiple children, make sure to use an array instead of an object

Encountering an error: How can I resolve this issue in React? The file relates to the layout I am utilizing Visual Studio export default class Layout extends React.Component { constructor(props) { super(props); this.identify = this.identify.bi ...

Leveraging ES6 Generators for Efficient XMLHttpRequests

My goal is to simplify AJAX calls using ES6 generators, but I've encountered some issues: let xhr = new XMLHttpRequest() function *statechange() { yield xhr.readyState; } let gen = statechange(); xhr.open("GET", myUrl, true); xhr.onreadystatec ...

Creating a Dynamic Shout Box with jQuery

Last week, I sought advice on Stack Overflow on how to create a shout box in ASP.NET. The suggested solution was to use AJAX updatepanel, triggers, and a timer. Following those instructions, I successfully developed my own shoutbox. However, the issue aro ...

What is the best way to ensure that TwentyTwenty.js images are always positioned in the

Looking to utilize the TwentyTwenty.js code for image comparison, but facing an issue where the images are aligned to the left side. Is there a way to keep them centered without explicitly setting the width on the container? <div id="beforeafter" class ...

When combining <a> with the class line-through, the line does not appear

I am currently utilizing a class to replace the deprecated strike in HTML: .entfall { text-decoration: line-through; } However, when using Firefox 38.x and the following code: <span class="entfall"><a href="some link">text</a></span ...

When using dynamic handler assignment within useEffect, the updated state is not reflected in the handler

Check out this code snippet: const App = () => { const [items, setItems] = useState<{ text: string; onClick: () => any }[]>([]) useEffect(() => setItems([ { text: 'Click me', onClick: handleButtonClick, } ...

What is the process for extracting information from a middleware within a Next.js framework?

I have been working on developing an authentication system using JWT in Next.js. In order to achieve this, I created a middleware that can validate the JWT token and establish an authentication process as shown below: export default function middleware(req ...

Encountering the error message "Uncaught TypeError: $.ajax is undefined"

Recently, I encountered an issue with my form that utilizes ajax to send user information to a php file. The form is embedded within a bootstrap modal and was functioning perfectly until I attempted to add an extra field for enhanced functionality. However ...

Displaying a base64 image in a new tab with JavaScript on iOS devices

Currently, I am receiving base64 data for an image and would like to open it in a new tab. To achieve this, my code looks something like this: var window = new window(); window.open("<iframe src="+base64Url+"); Interestingly, this method works perfec ...

A comprehensive guide on how to find keywords within an array and then proceed to make all text within the parent div tag stand

I am currently looking for a webpage that displays a list of products based on keywords from an array. Once it detects any word in the array, it highlights it with a red background - everything is working smoothly so far. However, I now wish for the script ...

What is the best approach for establishing an asynchronous connection to a MongoDB database?

Managing a MongoDB database using JavaScript and Node.js with Mongoose, I needed to retrieve an array containing the names of all collections in the database. Taking this into consideration, I implemented the following code snippet. let connection = mongoo ...

In the event of a 404 error, simply direct the user to the pageNotFound before ultimately guiding them back

I'm developing a website with Node JS and I want to implement a feature where if the user attempts to navigate to a non-existent page, they are redirected to a "Page Not Found" message before being automatically taken back to the home page after a few ...

Tips for enhancing your HTML email template with borders:

I designed an email template using the email template editor and incorporated nested table tags for each mail element. As I created a table to contain all these elements and attempted to add borders to the tags, I encountered a space between the top and bo ...

The export feature in the Datatable is currently experiencing technical difficulties

Can someone please assist me in troubleshooting why the data table export feature is not functioning on the provided link? jQuery: var table = $('#example').DataTable({ "ordering": false, buttons: [{ extend: "print", ...

Sending a message through Discord.JS to a designated channel

Recently diving into Discord.JS, I am struggling to understand how to make my bot send a message to the General Chat when a new user joins. Many examples I've come across suggest using the following code: const channel = client.channels.cache.find(ch ...

Steps to assign a value to a variable upon clicking on text

Struggling to create a form using HTML, CSS, and PHP. The concept involves selecting an option from a dropdown menu and picking a date on a calendar. However, the challenge lies in sending a value to a variable in PHP upon clicking a day. Once the value ...

Implement a delay before sending a new ajax request with jQuery in order to optimize performance

I've got a collection of hyperlinks that lead to various HTML pages. <ul id="item-list"> <li><a href="assets/data/item1.html">Item 1</a></li> <li><a href="assets/data/item2.html& ...

The page keeps refreshing repeatedly

Can someone help me troubleshoot this url modification script? var currentPath = window.location.href currentPath=currentPath.replace(/&amp;/g, "&"); window.location.href=path; It seems like the page keeps reloading endlessly... Any sugg ...

What is causing `foo()` to function in this specific scenario?

Check out this code snippet: https://jsfiddle.net/5k10h27j/ I'm puzzled by why foo() is being called as an argument to a non-existent function. function foo(){ alert('huh??'); } jQuery('#container').on('change', ...