How To Recognise Text File From My Linux Pc Via Django Code Without Checking Its Extension And Also Its File Size?
Solution 1:
You probably want to detect the upload's MIME type regardless of file extension, and that's often done by reading the file header to detect "magic numbers" or other bit patterns indicating the true nature of a file. Often text files are an edge case, where no header is detected and the first x bytes are printable ASCII or Unicode.
While that's a bit of a rabbit hole to dive into, there's a few Python libraries that will do that for you. For example: https://github.com/ahupp/python-magic will work for your needs by simply inferring the mime type per the file contents, which you will then match against the types you want to accept.
A somewhat related set of example code specific to your needs can be found here: https://stackoverflow.com/a/28306825/7341881
Edit: Eddie's solution is functionality equivalent; python-magic wraps libmagic, which is what Linux's native "file" command taps into. If you do decide to go the subprocess route, do be extra careful you're not creating a security vulnerability by improperly sanitizing user input (eg the user's provided filename). This could lead to an attack granting arbitrary access to your server's runtime environment.
Solution 2:
Easy 3 line solution with no external dependencies.
import subprocess
file_info = subprocess.getoutput('file demo')
print(file_info)
In POSIX systems (Linux, Unix, Mac, BSD etc) you can use a file
command, for example file demo
will display the file info even if the file extension is not explicitly set.
demo
is the argument for the file
command in other words the actual file you are trying to detect.
Disclaimer, be extra careful running external commands.
Please follow this link for more info about the Python subprocess
module.
https://docs.python.org/3.6/library/subprocess.html
Post a Comment for "How To Recognise Text File From My Linux Pc Via Django Code Without Checking Its Extension And Also Its File Size?"