How to get the extension of a file in Django?

2019-06-08 05:34发布

问题:

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!

回答1:

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


回答2:

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



回答3:

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)


回答4:

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]