1

I am testing for cleaned_data['content'].size > MAX_SIZE in forms to validate the upload size.

When googling how to check the length for an upload in Django, I came across several places (links below) where people are using some format (seemingly based on powers of 2 somehow) to represent MBs in bytes.

I guess there must be a good reason.

Why use such a format ? And how do you calculate the values below? (taken from the linked SO question)

# 2.5MB - 2621440
# 5MB - 5242880
# 10MB - 10485760
# 20MB - 20971520
# 50MB - 5242880
# 100MB 104857600
# 250MB - 214958080
# 500MB - 429916160

Django File upload size limit
https://djangosnippets.org/snippets/1303/
https://django-filebrowser.readthedocs.org/en/3.5.2/settings.html

Community
  • 1
  • 1
lajarre
  • 4,910
  • 6
  • 42
  • 69

1 Answers1

1

just because a kilobyte is 1024 bytes... with bytes the 'round numbers' are powers of 2 rather than 10

strictly speaking 1024 bytes is a "kibibyte" and according to SI units, a "kilobyte" is 1000 bytes, just like a kilogram is 1000 grams

however operating systems such as Windows tend to use the former definition

So for example if you want to limit upload size to 2MB you should use 2 * 2**20 (or 2 x 1024**2)

or general form for n MB would be n * 1024**2

http://en.wikipedia.org/wiki/Megabyte#Definitions

Anentropic
  • 32,188
  • 12
  • 99
  • 147
  • Thanks! But I still don't understand how to calculate 250MB and 500MB in the example that I added in the question – lajarre Jan 15 '15 at 09:51
  • see the last sentence of my answer, i.e. `n = 250` or `n = 500` – Anentropic Jan 15 '15 at 12:58
  • Doesn't match (500MB gives 524 288 000). So probably it's just an error in their stuff then? – lajarre Jan 15 '15 at 14:37
  • try Google: https://www.google.co.uk/webhp#q=500mb+in+bytes ...it gives SI units (i.e. 5 hundred million), if you switch to 'Mebibytes' you get the same as my answer – Anentropic Jan 16 '15 at 12:13
  • in that SO answer their figures are mostly right but it looks like their value for 250MB is actually 205MB (perhaps a typo on the calculator...), then they double that to get a value for 500MB which is really 410MB (strictly 'Mebibytes') – Anentropic Jan 16 '15 at 12:17