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
Barbara StreisandOriginal
2024-12-06 05:38:10820browse

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`);
    }
  }
});

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!

Statement:
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