Home > Web Front-end > JS Tutorial > How to Get File Size and Image Dimensions Before Uploading?

How to Get File Size and Image Dimensions Before Uploading?

Barbara Streisand
Release: 2024-12-06 05:38:10
Original
839 people have browsed it

How to Get File Size and Image Dimensions Before Uploading?

How to Obtain File Size, Image Dimensions before Uploading

In the realm of web development, it's often necessary to retrieve key details about files prior to uploading them to a website. This information, such as file size, image width, and height, can aid in validating file format, optimizing upload efficiency, and providing users with relevant feedback.

Using the File API with jQuery or JavaScript:

HTML5's File API offers a comprehensive suite of functions for accessing file-related information. Leveraging this API in conjunction with jQuery or JavaScript, you can seamlessly capture these details before initiating the upload process.

The following example demonstrates how to use both the File API and jQuery to fetch and display the desired information:

$('#browse-input').change(function() {
  let files = this.files;
  
  // Iterate through each selected file
  for (let i = 0; i < files.length; i++) {
    let file = files[i];
    
    // Extract desired information from each file
    let size = file.size;
    let width, height;
    
    // Check if file is an image and extract image dimensions if so
    if (file.type.match('image/*')) {
      let img = new Image();
      
      img.onload = function() {
        width = img.width;
        height = img.height;
        // Display extracted information
        console.log(`File: ${file.name}, Size: ${size} bytes, Width: ${width}px, Height: ${height}px`);
      };
      
      img.src = URL.createObjectURL(file);
    } else {
      // Display information for non-image files
      console.log(`File: ${file.name}, Size: ${size} bytes`);
    }
  }
});
Copy after login

By incorporating this solution, you empower users with a comprehensive view of the files they intend to upload, enabling them to make informed decisions and streamline the upload process.

The above is the detailed content of How to Get File Size and Image Dimensions Before Uploading?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template