Marcos Aguayo
Marcos Aguayo

Reputation: 7170

How to get the extension of a file in Django?

I'm building a web app in Django. I have a form that sends a file to views.py.

Views:

@login_required(login_url=login_url)
def addCancion(request):
    if request.method == 'POST':
        form2 = UploadSong(request.POST, request.FILES)
        if form2.is_valid():
            if(handle_uploaded_song(request.FILES['file'])):
                path = '%s' % (request.FILES['file'])
                ruta =  "http://domain.com/static/canciones/%s" % path
                usuario = Usuario.objects.get(pk=request.session['persona'])
                song = Cancion(autor=usuario, cancion=ruta)
                song.save()
                return HttpResponse(ruta)
            else:
                return HttpResponse("-3")
        else:
            return HttpResponse("-2")
    else:
        return HttpResponse("-1")   

I'm trying to upload only the MP3 files, but I don't know how to make this filter. I tried a class named "ContentTypeRestrictedFileField(FileField):" and doesn't work.

How can I get the file type in views.py?

Thanks!

Upvotes: 10

Views: 33069

Answers (7)

Pablo
Pablo

Reputation: 1071

You can use request.FILES["file_field_name"].content_type

my_file = request.FILES["file_field_name"]
if my_file.content_type != 'text/csv':
    print("Your file must be a CSV type")

Upvotes: 2

michal-michalak
michal-michalak

Reputation: 1155

Using MimeTypes().guess_extension() method. Check snippet below.

# guess the file extension
file_obj.seek(0)
mime = magic.from_buffer(file_obj.read(), mime=True)
extension = mimetypes.MimeTypes().guess_extension(mime)
>>> print extension
.jpeg

Upvotes: 0

Marcelo Soares
Marcelo Soares

Reputation: 63

Using FileType.py library.

Example:

kind = filetype.guess('tests/fixtures/sample.jpg')
if kind is None:
    print('Cannot guess file type!')
    return

print('File extension: %s' % kind.extension)
print('File MIME type: %s' % kind.mime)

Upvotes: 1

catherine
catherine

Reputation: 22808

You mean this:

u_file = request.FILES['file']            
extension = u_file.split(".")[1].lower()

if(handle_uploaded_song(file)):
    path = '%s' % u_file
    ruta =  "http://example.com/static/canciones/%s" % path
    usuario = Usuario.objects.get(pk=request.session['persona'])
    song = Cancion(autor=usuario, cancion=ruta)
    song.save()
    return HttpResponse(content_type)

Upvotes: 5

A. Chiele
A. Chiele

Reputation: 61

for get direct of request:

import os


extesion = os.path.splitext(str(request.FILES['file_field']))[1]

or get extesion in db - model.

import os

file = FileModel.objects.get(pk=1)  # select your object
file_path = file.db_column.path  # db_column how you save name of file.

extension = os.path.splitext(file_path)[1]

Upvotes: 6

dleal
dleal

Reputation: 660

You could also use the clean() method from the form, which is used to validate it. Thus, you can reject files that are not mp3. Something like this:

class UploadSong(forms.Form):
    [...]

    def clean(self):
        cleaned_data = super(UploadSong, self).clean()
        file = cleaned_data.get('file')

        if file:
            filename = file.name
            print filename
            if filename.endswith('.mp3'):
                print 'File is a mp3'
            else:
                print 'File is NOT a mp3'
                raise forms.ValidationError("File is not a mp3. Please upload only mp3 files")

        return file

Upvotes: 16

lajarre
lajarre

Reputation: 5162

with import mimetypes, magic:

mimetypes.MimeTypes().types_map_inv[1][
    magic.from_buffer(form.cleaned_data['file'].read(), mime=True)
][0]

gives you the extension as '.pdf' for example

https://docs.djangoproject.com/en/dev/topics/forms/#processing-the-data-from-a-form
http://docs.python.org/2/library/mimetypes.html#mimetypes.MimeTypes.types_map_inv
https://github.com/ahupp/python-magic#usage

Upvotes: 7

Related Questions