Uploading files with previews and no option to alter the image dimensions

I am having trouble with resizing an image preview before submitting it. Despite setting the width and height to 1px in both the div and image, it still displays at its normal dimensions.

$(function() {
    var imagesPreview = function(input, placeToInsertImagePreview) {

        if (input.files) {
            var filesAmount = input.files.length;

            for (i = 0; i < filesAmount; i++) {
               var reader = new FileReader();

               reader.onload = function(event) {
                 $($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
                 }

                 reader.readAsDataURL(input.files[i]);
                 }
              }
          };

          $('#upload-image').on('change', function() {
              imagesPreview(this, 'img.image');
       });
   });
div.img_container {
    max-width: 1px;
    max-height: 1px;
}
img.image {
    width: 1px;
    height: 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action='upload.php' method='post' enctype='multipart/form-data'>
   <input id='upload-image' type='file' name='files[]' multiple>
   <input type='submit' value='Upload'>
</form>
<div class='img_container'><img class='image'></div>

Answer №1

Make sure to update the src of the image and not append it into another image:

$(function() {
  var imagesPreview = function(input, img) {

    if (input.files) {
      var filesAmount = input.files.length;

      for (i = 0; i < filesAmount; i++) {
        var reader = new FileReader();

        reader.onload = function(event) {
          $(img).attr('src', event.target.result)
        }

        reader.readAsDataURL(input.files[i]);
      }
    }

  };

  $('#upload-image').on('change', function() {
    imagesPreview(this, 'img.image');
  });
});
img.image {
  width: 100px;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action='upload.php' method='post' enctype='multipart/form-data'>
  <input id='upload-image' type='file' name='files[]' multiple>
  <input type='submit' value='Upload'>
</form>
<div class='img_container'><img class='image'></div>

Answer №2

@Kosh Very beat you to it here :)

Next time, I suggest taking a look at the code in the inspector.

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

Having trouble achieving the desired effect with inline block

I'm having some trouble creating a simple store page. One of the products is supposed to look like this: However, it's currently showing up like this: I've been attempting to use inline block so that I can have the negotiate button and pro ...

Create a Bootstrap div containing a button that adjusts to different screen sizes on the

Struggling with an issue in Bootstrap on how to create an input group with responsive content and a button on the right side. I want the button to always be on the right side and also responsive. I attempted to achieve this with the code below, but it does ...

Updating Mysql through REST API/JWT using PUT method is not possible

I have been attempting to send an update request using Jwt (Tokens) and Node.Js with a backend in mysql. While Postman confirms that the record has been successfully updated, I am unable to locate where the actual update occurred. No changes seem to be ref ...

I'm struggling to make background-image display properly in my CSS code

In my quest to enhance the appearance of my website, I've been grappling with getting the background-image property to cooperate in CSS for the past three days. It's frustrating because I've successfully implemented this feature before, but ...

What is preventing the buttons from filling the entire space of the parent element in this case?

https://i.stack.imgur.com/kbiWi.png I'm trying to figure out how to make the Repos and Stars buttons fill the entire height of their parent container, similar to the Github icon. Unfortunately, the code below is not achieving this effect. I attempted ...

The Ultimate Guide to Initializing Variables in UI Router State Access

In my application, I have defined 2 states. One is "tickets" which matches /tickets ... $stateProvider // defines the states of my application .state("tickets", { // assigns properties to each state url: "/tickets", // route templateUrl: "m ...

Confirm the dimensions of an image prior to uploading using Node, Express, and Multer

Currently, I am developing a project using Nodejs with the express framework and ejs as the view engine. I have encountered an issue while working on image uploads. I am utilizing Multer for this task, but I need to implement a requirement where images wil ...

converting an angular object into a string representation

I stumbled upon this guide: . and it includes the following piece of code: import { Component } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl ...

Trouble with React Material Modal TransitionProps triggering onEntering event

Currently, I am in the process of updating Material UI to version 5. Initially, I encountered an error stating that onEntering is deprecated and should be replaced with transitionprops. There is a specific method (let's name it doSomething) that I wa ...

The $scope variable does not sync with the express API

I have noticed that the static part of my app is loading fine. Recently, I integrated a service using Express as a simple API. However, when I attempt to set the #scope from my module's controller, it seems like it hasn't loaded at all. I am puzz ...

The Angular model does not automatically refresh when the Space or Enter key is pressed

Having an issue with my editable div and the ng-trim attribute. Even though I have set ng-trim to false, pressing SPACE or ENTER does not increment the string length by one in the div below. Using Angular 1.3.x and wondering if anyone has any ideas on how ...

Unable to execute xmlHttp.responseXML on a server that is offline

Currently, I am diving into the world of AJAX and XML. However, I recently encountered a frustrating issue. I attempted to create a basic program that would display everything I input into an input box within a <div>. Strangely enough, my program fa ...

Connecting a specific URL of an API to a single mobile app: A step-by-step guide

Currently, my API includes a user registration system that is utilized by a mobile application. Most of the URLs are restricted for anonymous users and require a token key for authorization, except for the register URL. The register URL needs to remain op ...

A guide on iterating through a JSON object in Vue and Javascript to retrieve keys and values, checking if they are either distinct or null

Looking for a way to iterate through a JSON object that may or may not have properties fields, which can be null or contain various configurations. I need to display it in a code block. Below is the example JSON data: "grade": [ { ...

Using Firebase with the async pipe in Angular 5

I am struggling to implement async pipe in Angular firebase and encountering an error that I cannot resolve: ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' Utilizing the Firebase NoSQL database: { "bos ...

Tips on obtaining the element selector when a div is being dynamically loaded during an AJAX call

When running two ajax calls, I encounter an issue where the second call loads some HTML onto the page that is needed for processing a specific div in the first call. However, since the div is not present until after the second call is completed, I receiv ...

Adjusting the properties of an element with Javascript

My goal is to dynamically set the value of a parameter within a <script> element using JavaScript. I am using the Stripe checkout.js and I want to populate the Email input field with a value obtained from another text box on the page. Here's how ...

How to retrieve the selected values of specific option tags using jQuery?

I have a situation where I need to select an option from a dropdown menu. Here is the code for the dropdown: <select id="customUser_id" name="customUser_id"> <option value="2" label="Friends Of Friends">Friends Of Friends</option> &l ...

Extracting CSS data and storing it in a SQL database

Hello there, I've created a div using CSS like this: echo '#'. $pess2['naam'] .' { width: 190px; height: 90px; padding: 0.5em; float: left; left:'. $pess2['left'] .'px; top:'. $pess2['top'] ...

Socketio: Issue: Isolated surrogate U+D83D is not a valid scalar value

I've been experiencing frequent crashes with my node.js server recently, all due to a recurring socket.io error. It seems that the client may be sending invalid UTF strings, causing an error in the utf8.js file. I'm getting frustrated with the co ...