Home  >  Article  >  Web Front-end  >  How to Determine File Size Before Uploading with AJAX/PHP?

How to Determine File Size Before Uploading with AJAX/PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-10-30 07:11:03428browse

How to Determine File Size Before Uploading with AJAX/PHP?

Determining File Size Before Uploading with AJAX/PHP

When handling file uploads, it's often useful to ascertain the file size before initiating the upload process. This information can help in validating file sizes, managing storage limitations, or providing progress updates during the upload.

For fetching file size before uploading using AJAX and PHP, follow these steps:

JavaScript (using jQuery):

Attach a change event handler to the HTML input element representing the file upload:

<code class="javascript">$('#myFile').bind('change', function() {
  // this.files[0].size returns the file size in bytes.
  alert(this.files[0].size);
});</code>

PHP (assuming the file size is transmitted via AJAX):

<code class="php"><?php
if (isset($_FILES['myFile'])) {
  // $_FILES['myFile']['size'] contains the file size in bytes.
  $fileSize = $_FILES['myFile']['size'];
  // Handle the file size as needed.
}</code>

By leveraging the above approach, you can determine the file size before uploading the file to your server, enabling you to handle file uploads more efficiently.

The above is the detailed content of How to Determine File Size Before Uploading with AJAX/PHP?. 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