Checking Selected Image Size Before Upload Using the File API

プログラミング・Web開発カテゴリを表すパンダのイラスト Programming / Web Development

About This Article
This article is generated through an automated workflow utilizing generative AI. Based on MDN documentation for the File API, Blob.size, createObjectURL, and revokeObjectURL, as well as the W3C File API Editor's Draft, it explains the concepts using existing demo input fields, file information displays, and preview URL cleanup processing.

Verification Status: 📘 Official information verified, static code checked, browser physical device untested

When an image upload interface only tells you the file is too large after submission, it causes unnecessary delays and forces you to select another file. Displaying the file name, size, and visual preview before upload allows users to compare candidates on the spot. Using the browser's File API, you can read selected file information and generate a local preview without sending data to the server.

Live Demo: Select an Image to Compare File Size and Preview

What You Will Test in This Article

ItemDescription
Target AudienceIndividuals who want to learn the basics of HTML forms and JavaScript
ActionClick Run and select an image from the file picker
ObservationThe selected image, file name, and exact byte size are displayed
ComparisonReselect images of different sizes to compare file capacity and visual appearance
Execution EnvironmentBrowsers supporting File inputs, the File API, and Blob URLs
Data handlingThe demo code does not upload or save selected files. Diagram rendering uses the Mermaid CDN.

Operating the demo

  1. Open the live demo and click "Run". A file selection button will appear in the shared experiment section.

  2. Select a single image from your local device.

  3. Verify the file name and byte count in the results section.

  4. Select a different image and compare the values and display.

In the example result, the file name is displayed as photo-a.jpg and the byte count as 245760. This is an illustrative example and differs from the values of your local image. The selection field sets accept="image/*" to make it easier to select images.

What happens with the File API

<input type="file"> The files represents a list of File objects corresponding to the selected files. This demo extracts the first files[0] and displays file.name and file.size. The unit for size is bytes. The file size is not the pixel dimensions of the image nor its rendered size on the screen. Even with the same dimensions, the file size varies depending on the image format, compression rate, and image content.

Previews are created using URL.createObjectURL(file). The browser generates a temporary URL pointing to the selected File, which can be specified in img.src to render it. There is no need to convert file contents to strings or perform upload processing.

const input = document.querySelector("#image");
const info = document.querySelector("#info");
const preview = document.querySelector("#preview");
let previewUrl = null;

input.addEventListener("change", () => {
  // 古い一時URLを解放してから、新しいファイルを表示する。
  if (previewUrl) URL.revokeObjectURL(previewUrl);
  const file = input.files[0];
  if (!file) {
    preview.removeAttribute("src");
    info.textContent = "画像を選んでください。";
    previewUrl = null;
    return;
  }
  previewUrl = URL.createObjectURL(file);
  preview.src = previewUrl;
  info.textContent = file.name + " / " + file.size + " bytes";
});

This is a short example showing the key points. In the actual demo, the common runner generates a file input after "Run". When a file is selected, if the image can be loaded, it appears in the preview, and File.name and File.size are displayed in the results section. Simply running it without selecting anything yields no result value.

Observe by Changing Conditions

Conditions to TestWhat to ObserveWhat Can Be Deduced
Small JPEG vs. Large JPEGByte count and appearanceFile size changes depending on compression and content, even with the same format.
JPEG vs. PNGByte count, previewFile size magnitude cannot be determined by the format name alone.
Landscape image vs. Portrait imagePreviewThe appearance changes, but this demo does not quantify dimensions.
Reselecting the same imageFile name and byte countThe same file will normally yield the same information.

When converting to KB or MB displays, separate the values for screen display and validation. For example, 1 MiB is 1,048,576 bytes. Even if decimal places are rounded on the screen, the original integer value is used for comparison against the size limit. If the limit is 5 MiB,file.size > 5 * 1024 * 1024, comparing in byte units prevents boundary misinterpretation due to display rounding.

When using in production

It can be used in forms where users review candidates after selection, such as profile images, support attachments, or internal application proofs. Displaying a message like "The selected image is 2.4 MB; the limit is 5 MB" early helps users decide to reselect without waiting for submission. Image previews also make it easier to notice if the wrong photo or orientation was chosen.

However, client-side display serves as user guidance, not server-side security validation.accept="image/*" is a hint to narrow down candidates on the selection screen and does not guarantee format or content. The server re-verifies the file size, allowed formats, whether it can actually be decoded, file name handling, and authentication/authorization. Do not determine the image format solely by its extension.

Cleaning up object URLs

createObjectURL() The URL returned by is a temporary reference. Release the previous URL with revokeObjectURL() before switching to the next image, and clean it up when exiting the screen as well. Implementing only the creation process while forgetting the disposal process can cause unnecessary resources to be held on screens where re-selection is repeated. The common runner releases URLs upon re-selection and demo termination.

Troubleshooting

  • No result appears after selection: Check whether "Execute" was pressed first and whether the file picker appeared in the input field.

  • Image does not display: Reselect with another common image. Even if the extension indicates an image, it may not display if it is corrupted or in a format the browser cannot decode.

  • Size is larger than expected: Check the number of bytes in file.size rather than the display dimensions. This varies depending on compression quality and image content.

  • Non-image files can be selected: accept is not a security check. Server-side validation is required.

  • Diagrams do not display: Diagrams fetch rendering code from the Mermaid CDN. If network communication is restricted, refer to the diagram description and the source within the HTML.

  • Old preview remains even after re-selection: Verify that the change handler updates img.src and revokes the unnecessary old URL.

Constraints and Privacy

The code in this demo does not transmit selected files, using Object URLs exclusively for in-page previews. The educational material also contains no logic for persistently storing files. However, site-wide communication cannot be guaranteed by the text body alone. Before handling images containing personal information in a production service, verify the destination of all communications, including other site scripts and browser extensions.

Large images consume memory and may take time to decode. When previewing multiple images at once, limit the number retained simultaneously and consider generating downscaled images or implementing cancellation handling. This demo does not read dimensions or EXIF orientation metadata. When adding features that handle location metadata, separately design the display, deletion, and sharing purposes alongside privacy considerations.

Official Documentation

GitHub Sample

Course README / Demo HTML / Shared JavaScript

Verification Scope

I statically verified the HTML and common runner, checking the file input with configuration ID 51, accept attribute, files[0], name, and size upon the change event, the creation of the Object URL, and the revocation during re-selection and cleanup. The steps in the README have also been revised to follow the same order. Actual operation on GitHub Pages could not be verified from this execution environment. Browser execution, cross-browser comparison, assistive technology verification, and network traffic capture were not performed.

Document information

Article title
Checking Selected Image Size Before Upload Using the File API
Published
Updated
Source
https://papanda925.com/?p=19028&lang=en

License: Text and original figures for which this site holds the relevant rights are available under CC BY 4.0 , unless otherwise noted. This article may include content created or edited with generative AI. If code has a separate license notice or a linked GitHub repository license, that license takes precedence for the code. Quotations, third-party materials, images, and trademarks are excluded from this license. Usage policy

Copied title and URL