Detecting File Upload Size on the Client Side

Detecting file upload size on the client side?

On MAX_FILE_SIZE

Read This:

...At http://pk.php.net/manual/en/features.file-upload.post-method.php and equivalent locations in other formats, it is stated
that browsers take the value of a MAX_FILE_SIZE form field into
account.

This information is repeated elsewhere on the web and in books, but
appears to originate from the PHP documentation (it does not appear in
terms of other server-side technologies
).

There is nothing in any of the HTML, HTTP or related specs to indicate
that this is the case (in particular RFC 1867 which introduced file
uploads to HTML doesn't mention it
, so it isn't even a case of a kludge
that was mentioned in the first RFC and then dropped) nor does it make
sense in the context of the HTML specs (there is nothing to indicate any
relationship between that particular hidden input and the file input).
The only statements about hidden fields I could find in any of them was
warnings in the security considerations sections against user-agents
basing any file-related operations on anything mentioned in a hidden
field.

No browsers appear to perform this as an "extension". Indeed given that
there are potentially other possible meanings for a hidden field with
that name in an application handling several file uploads, it would have
to be considered a design flaw any any did.

I submit that there is no such mechanism in mainstream browsers (if any
at all) and indeed shouldn't be. Reference to it should be dropped from
documentation.

I'd further suggest that since this idea has propagated from this
documentation elsewhere that a note about it not working should to be
added.

If a mechanism is required or desired for more rapidly handling this
sort of file handling issue then it requires functionality to allow PHP
to intercept streams being uploaded before request completion, which
would be completely different to how this documentation suggest it
should be dealt with, even if it was true...

  • http://www.juangiordana.com.ar/blog/2007/12/08/max_file_size-erroneo/

the code below come from swfUpload php implementation:

// Check post_max_size (http://us3.php.net/manual/en/features.file-upload.php#73762)
$POST_MAX_SIZE = ini_get('post_max_size');
$unit = strtoupper(substr($POST_MAX_SIZE, -1));
$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));

if ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) {
header("HTTP/1.1 500 Internal Server Error");
echo "POST exceeded maximum allowed size.";
exit(0);
}
// Validate the file size (Warning the largest files supported by this code is 2GB)
$max_file_size_in_bytes = 2147483647;
$file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
if (!$file_size || $file_size > $max_file_size_in_bytes) {
HandleError("File exceeds the maximum allowed size");
exit(0);
}

Client Checking file size using HTML5?

This works. Place it inside an event listener for when the input changes.

if (typeof FileReader !== "undefined") {
var size = document.getElementById('myfile').files[0].size;
// check file size
}

MVC FileUpload file size client side validation

I dont think there is currently a cross browser way to do what you want, check this question

This can work only in webkit based browsers for example

var size = document.getElementById('file').files[0].size;

JavaScript file upload size validation

Yes, you can use the File API for this.

Here's a complete example (see comments):

document.getElementById("btnLoad").addEventListener("click", function showFileSize() {
// (Can't use `typeof FileReader === "function"` because apparently it
// comes back as "object" on some browsers. So just see if it's there
// at all.)
if (!window.FileReader) { // This is VERY unlikely, browser support is near-universal
console.log("The file API isn't supported on this browser yet.");
return;
}

var input = document.getElementById('fileinput');
if (!input.files) { // This is VERY unlikely, browser support is near-universal
console.error("This browser doesn't seem to support the `files` property of file inputs.");
} else if (!input.files[0]) {
addPara("Please select a file before clicking 'Load'");
} else {
var file = input.files[0];
addPara("File " + file.name + " is " + file.size + " bytes in size");
}
});

function addPara(text) {
var p = document.createElement("p");
p.textContent = text;
document.body.appendChild(p);
}
body {
font-family: sans-serif;
}
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load'>
</form>

How to read and echo file size of uploaded file being written at server in real time without blocking at both server and client?

You need to clearstatcache to get real file size. With few other bits fixed, your stream.php may look like following:

<?php

header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
header("Connection: keep-alive");
// Check if the header's been sent to avoid `PHP Notice: Undefined index: HTTP_LAST_EVENT_ID in stream.php on line `
// php 7+
//$lastId = $_SERVER["HTTP_LAST_EVENT_ID"] ?? 0;
// php < 7
$lastId = isset($_SERVER["HTTP_LAST_EVENT_ID"]) ? intval($_SERVER["HTTP_LAST_EVENT_ID"]) : 0;

$upload = $_GET["filename"];
$data = 0;
// if file already exists, its initial size can be bigger than the new one, so we need to ignore it
$wasLess = $lastId != 0;
while ($data < $_GET["filesize"] || !$wasLess) {
// system calls are expensive and are being cached with assumption that in most cases file stats do not change often
// so we clear cache to get most up to date data
clearstatcache(true, $upload);
$data = filesize($upload);
$wasLess |= $data < $_GET["filesize"];
// don't send stale filesize
if ($wasLess) {
sendMessage($lastId, $data);
$lastId++;
}
// not necessary here, though without thousands of `message` events will be dispatched
//sleep(1);
// millions on poor connection and large files. 1 second might be too much, but 50 messages a second must be okay
usleep(20000);
}

function sendMessage($id, $data)
{
echo "id: $id\n";
echo "data: $data\n\n";
ob_flush();
// no need to flush(). It adds content length of the chunk to the stream
// flush();
}

Few caveats:

Security. I mean luck of it. As I understand it is a proof of concept, and security is the least of concerns, yet the disclaimer should be there. This approach is fundamentally flawed, and should be used only if you don't care of DOS attacks or information about your files goes out.

CPU. Without usleep the script will consume 100% of a single core. With long sleep you are at risk of uploading the whole file within a single iteration and the exit condition will be never met. If you are testing it locally, the usleep should be removed completely, since it is matter of milliseconds to upload MBs locally.

Open connections. Both apache and nginx/fpm have finite number of php processes that can serve the requests. A single file upload will takes 2 for the time required to upload the file. With slow bandwidth or forged requests, this time can be quite long, and the web server may start to reject requests.

Clientside part. You need to analyse the response and finally stop listening to the events when the file is fully uploaded.

EDIT:

To make it more or less production friendly, you will need an in-memory storage like redis, or memcache to store file metadata.

Making a post request, add a unique token which identify the file, and the file size.

In your javascript:

const fileId = Math.random().toString(36).substr(2); // or anything more unique
...

const [request, source] = [
new Request(`${url}?fileId=${fileId}&size=${filesize}`, {
method:"POST", headers:headers, body:file
})
, new EventSource(`${stream}?fileId=${fileId}`)
];
....

In data.php register the token and report progress by chunks:

....

$fileId = $_GET['fileId'];
$fileSize = $_GET['size'];

setUnique($fileId, 0, $fileSize);

while ($uploaded = stream_copy_to_stream($input, $file, 1024)) {
updateProgress($id, $uploaded);
}
....

/**
* Check if Id is unique, and store processed as 0, and full_size as $size
* Set reasonable TTL for the key, e.g. 1hr
*
* @param string $id
* @param int $size
* @throws Exception if id is not unique
*/
function setUnique($id, $size) {
// implement with your storage of choice
}

/**
* Updates uploaded size for the given file
*
* @param string $id
* @param int $processed
*/
function updateProgress($id, $processed) {
// implement with your storage of choice
}

So your stream.php don't need to hit the disk at all, and can sleep as long as it is acceptable by UX:

....
list($progress, $size) = getProgress('non_existing_key_to_init_default_values');
$lastId = 0;

while ($progress < $size) {
list($progress, $size) = getProgress($_GET["fileId"]);
sendMessage($lastId, $progress);
$lastId++;
sleep(1);
}
.....

/**
* Get progress of the file upload.
* If id is not there yet, returns [0, PHP_INT_MAX]
*
* @param $id
* @return array $bytesUploaded, $fileSize
*/
function getProgress($id) {
// implement with your storage of choice
}

The problem with 2 open connections cannot be solved unless you give up EventSource for old good pulling. Response time of stream.php without loop is a matter of milliseconds, and it is quite wasteful to keep the connection open all the time, unless you need hundreds updates a second.



Related Topics



Leave a reply



Submit