Limit the file size that can be uploaded.
962563
function (options) {
    // Parse a string representing a file size and convert it into bytes.
    // A number on it's own will be assumed to be bytes. A multiple such as
    // "k" or "m" can be appended to the string to handle larger numbers. This
    // is case insensitive and uses powers of 1024 rather than (1000).
    // So both 1kB and 1kb == 1024.
    function parseLimit(string) {
      var matches = ('' + string).toLowerCase().match(regexp),
          bytes = null, power;

      if (matches) {
        bytes = parseFloat(matches[1]);
        power = powers[matches[2]];

        if (bytes && power) {
          bytes = Math.pow(bytes * 1024, power);
        }
      }

      return bytes || null;
    }

    var powers = { k: 1, m: 2, g: 3, t: 4 },
        regexp = /^(\d+(?:.\d+)?)\s*([kmgt]?)b?$/,
        limit  = options && parseLimit(options.limit);

    return function (req, res, next) {
      if (limit) {
        var contentLength = parseInt(req.header('Content-Length', 0), 10),
            message = 'Sorry, the content you have uploaded is larger than JS Bin can handle. Max size is ' + options.limit;

        if (limit && contentLength > limit) {
          return next(new errors.RequestEntityTooLarge(message));
        }
      }
      next();
    };
  }
865391
def size(self):
        """"""
        old = self.__file.tell()        # old position

        self.__file.seek(0, 2)          # end of file
        n_bytes = self.__file.tell()    # file size in bytes

        self.__file.seek(old)           # back to old position

        return n_bytes
634952
def file_size(self):
        """"""
        if self._file_size is None:
            if isinstance(self._path_or_fd, string_types()):
                self._file_size = os.stat(self._path_or_fd).st_size
            else:
                self._file_size = os.fstat(self._path_or_fd).st_size
            # END handle path type
        # END update file size
        return self._file_size
926005
def allow_rwe(self, name):
        """"""
        assert name in PERMISSIONS.keys()
        os.chmod(self.file_path, PERMISSIONS[name]['all'])
1301429
def safe_size(source):
    

    if source is None:
        return None

    total_bytes = 0
    bytes = []
    b = source.read(MIN_READ_SIZE)
    while b:
        total_bytes += len(b)
        bytes.append(b)
        if total_bytes > MAX_STRING_SIZE:
            try:
                data = FileString(TemporaryFile())
                for bb in bytes:
                    data.write(bb)
                del bytes
                del bb
                b = source.read(MIN_READ_SIZE)
                while b:
                    total_bytes += len(b)
                    data.write(b)
                    b = source.read(MIN_READ_SIZE)
                data.seek(0)
                Log.note("Using file of size {{length}} instead of str()",  length= total_bytes)

                return data
            except Exception as e:
                Log.error("Could not write file > {{num}} bytes",  num= total_bytes, cause=e)
        b = source.read(MIN_READ_SIZE)

    data = b"".join(bytes)
    del bytes
    return data
1290349
private function maxUploadFilesize(): string
    {
        $bytes = UploadedFile::getMaxFilesize();
        $kb    = intdiv($bytes + 1023, 1024);

        return I18N::translate('%s KB', I18N::number($kb));
    }
838003
def check_for_allowed_file(f):
    
    for ext in SUPPORTED_EXTENSIONS:
        if f.endswith(ext):
            return True
    log.error("Failed upload: Not an allowed file extension: %s", f)
    raise SystemExit
1227887
def make_limited_stream(stream, limit):
    """"""
    if not isinstance(stream, LimitedStream):
        if limit is None:
            raise TypeError('stream not limited and no limit provided.')
        stream = LimitedStream(stream, limit)
    return stream
349960
def limit_disk_io(self, uuid, media, totalbytessecset=False, totalbytessec=0, readbytessecset=False, readbytessec=0, writebytessecset=False,
                      writebytessec=0, totaliopssecset=False, totaliopssec=0, readiopssecset=False, readiopssec=0, writeiopssecset=False, writeiopssec=0,
                      totalbytessecmaxset=False, totalbytessecmax=0, readbytessecmaxset=False, readbytessecmax=0, writebytessecmaxset=False, writebytessecmax=0,
                      totaliopssecmaxset=False, totaliopssecmax=0, readiopssecmaxset=False, readiopssecmax=0, writeiopssecmaxset=False, writeiopssecmax=0,
                      totalbytessecmaxlengthset=False, totalbytessecmaxlength=0, readbytessecmaxlengthset=False, readbytessecmaxlength=0,
                      writebytessecmaxlengthset=False, writebytessecmaxlength=0, totaliopssecmaxlengthset=False, totaliopssecmaxlength=0,
                      readiopssecmaxlengthset=False, readiopssecmaxlength=0, writeiopssecmaxlengthset=False, writeiopssecmaxlength=0, sizeiopssecset=False,
                      sizeiopssec=0, groupnameset=False, groupname=''):
        
        args = {
            'uuid': uuid,
            'media': media,
            'totalbytessecset': totalbytessecset,
            'totalbytessec': totalbytessec,
            'readbytessecset': readbytessecset,
            'readbytessec': readbytessec,
            'writebytessecset': writebytessecset,
            'writebytessec': writebytessec,
            'totaliopssecset': totaliopssecset,
            'totaliopssec': totaliopssec,
            'readiopssecset': readiopssecset,
            'readiopssec': readiopssec,
            'writeiopssecset': writeiopssecset,
            'writeiopssec': writeiopssec,
            'totalbytessecmaxset': totalbytessecmaxset,
            'totalbytessecmax': totalbytessecmax,
            'readbytessecmaxset': readbytessecmaxset,
            'readbytessecmax': readbytessecmax,
            'writebytessecmaxset': writebytessecmaxset,
            'writebytessecmax': writebytessecmax,
            'totaliopssecmaxset': totaliopssecmaxset,
            'totaliopssecmax': totaliopssecmax,
            'readiopssecmaxset': readiopssecmaxset,
            'readiopssecmax': readiopssecmax,
            'writeiopssecmaxset': writeiopssecmaxset,
            'writeiopssecmax': writeiopssecmax,
            'totalbytessecmaxlengthset': totalbytessecmaxlengthset,
            'totalbytessecmaxlength': totalbytessecmaxlength,
            'readbytessecmaxlengthset': readbytessecmaxlengthset,
            'readbytessecmaxlength': readbytessecmaxlength,
            'writebytessecmaxlengthset': writebytessecmaxlengthset,
            'writebytessecmaxlength': writebytessecmaxlength,
            'totaliopssecmaxlengthset': totaliopssecmaxlengthset,
            'totaliopssecmaxlength': totaliopssecmaxlength,
            'readiopssecmaxlengthset': readiopssecmaxlengthset,
            'readiopssecmaxlength': readiopssecmaxlength,
            'writeiopssecmaxlengthset': writeiopssecmaxlengthset,
            'writeiopssecmaxlength': writeiopssecmaxlength,
            'sizeiopssecset': sizeiopssecset,
            'sizeiopssec': sizeiopssec,
            'groupnameset': groupnameset,
            'groupname': groupname,
        }
        self._limit_disk_io_action_chk.check(args)

        self._client.sync('kvm.limit_disk_io', args)
995388
def __allowed_extension(self, filename, extensions):
        
        allowed_extensions = current_app.config['UPLOADS']['EXTENSIONS']
        if extensions is not None:
            allowed_extensions = extensions
        return '.' in filename and filename.rsplit('.', 1)[1].lower() in \
            allowed_extensions
359877
public List<MultipartFile> validateFiles(List<MultipartFile> files, long maxLength, String[] allowExtName) {

        List<MultipartFile> retFiles = new ArrayList<MultipartFile>();

        for (MultipartFile multipartFile : files) {

            try {

                this.validateFile(multipartFile, maxLength, allowExtName);
                retFiles.add(multipartFile);

            } catch (Exception e) {

                LOG.warn(e.toString());
            }
        }

        return retFiles;
    }
1322497
def setUploadRateLimit(infoHash, bytesPerSecond)
      raise "upload rate limit must be an Integer, not a #{bytesPerSecond.class}" if bytesPerSecond && ! bytesPerSecond.is_a?(Integer)
      @handler.setUploadRateLimit(infoHash, bytesPerSecond)
    end
1184197
public void canUpload(String name, long fileSize) {
        URL url = UPLOAD_FILE_URL.build(this.getAPI().getBaseURL());
        BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, "OPTIONS");

        JsonObject parent = new JsonObject();
        parent.add("id", this.getID());

        JsonObject preflightInfo = new JsonObject();
        preflightInfo.add("parent", parent);
        preflightInfo.add("name", name);

        preflightInfo.add("size", fileSize);

        request.setBody(preflightInfo.toString());
        BoxAPIResponse response = request.send();
        response.disconnect();
    }
545054
public static function getFileUploadLimit()
    {

        $max_upload = self::toBytes(ini_get('upload_max_filesize'));
        $max_post = self::toBytes(ini_get('post_max_size'));
        $memory_limit = self::toBytes(ini_get('memory_limit'));

        $returnValue = min($max_upload, $max_post, $memory_limit);

        return (int)$returnValue;
    }
1360275
def _ensure_valid_record_size(self, size):
        """"""
        if size > self.config['max_request_size']:
            raise Errors.MessageSizeTooLargeError(
                "The message is %d bytes when serialized which is larger than"
                " the maximum request size you have configured with the"
                " max_request_size configuration" % (size,))
        if size > self.config['buffer_memory']:
            raise Errors.MessageSizeTooLargeError(
                "The message is %d bytes when serialized which is larger than"
                " the total memory buffer you have configured with the"
                " buffer_memory configuration." % (size,))
679838
@Nonnull
  public FineUploaderBasic setSizeLimit (@Nonnegative final int nSizeLimit)
  {
    ValueEnforcer.isGE0 (nSizeLimit, "SizeLimit");
    m_nValidationSizeLimit = nSizeLimit;
    return this;
  }
908416
public function resetSize() {

		$filePath	= $this->getFilePath();

		if( $filePath && file_exists( $filePath ) && is_file( $filePath ) ) {

			$size		= filesize( $filePath ); // bytes
			$sizeInMb	= $size / pow( 1024, 2 );

			$this->size = round( $sizeInMb, 4 ); // Round upto 4 precision, expected size at least in kb
		}
	}