I'm using an application which has the following line in it:
ACCEPT_FILE_TYPES = re.compile('image/(gif|p?jpeg|(x-)?png)')
Obviously, it limits uploads to images of the specified extensions. But I plan to use it for uploading these formats (perhaps even more than that)
I guess it needs to be rewritten to the following form:
ACCEPT_FILE_TYPES = re.compile('/(docx?|xlsx?|pdf|rar|zip|7z)')
Any help would be appreciated.
Those aren't file extensions that you're trying to match but MIME types.
The MIME types for common image formats happen to be quite straightforward, for example:
image/png
image/jpeg
image/gif
But most other types are not, but instead are using MIME types like these:
.pdf application/pdf
.doc application/msword
.xls application/vnd.ms-excel
.rar application/x-rar-compressed
.7z application/x-7z-compressed
.zip application/zip
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx application/vnd.openxmlformats-officedocument.spreadsheetml.template
.potx application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx application/vnd.openxmlformats-officedocument.presentationml.slideshow
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
.sldx application/vnd.openxmlformats-officedocument.presentationml.slide
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx application/vnd.openxmlformats-officedocument.wordprocessingml.template
Note: These are only the most commonly used MIME types for the respective file formats. The IANA is the official authority for registering MIME types, but in the wild you'll encounter many different variations, depending on the programs that use them (Mail clients, browsers, web servers, ...).
So you shouldn't be matching them by using regular expressions, but instead maintain a registry of allowed MIME types (can be a simple Python list, or a dictionary if you want to really make sure and account for variants).
Read up on MIME types, check the IANA MIME Media Types list as an authoritative source for registered MIME types and use the Python mimetypes
module to look up mimetypes by file extensior or vice versa.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With