如何在Django中获取文件的扩展名?

2024-06-25 23:57:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在Django建立一个网络应用程序。 我有一个表单将文件发送到views.py。

视图:

@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")   

我只想上传MP3文件,但我不知道如何制作这个过滤器。 我尝试了一个名为“ContentTypeRestrictedFileField(FileField):”的类,但它不起作用。

如何在views.py中获取文件类型?

谢谢!


Tags: 文件pyurlreturnifsongrequestlogin
3条回答

使用import mimetypes, magic

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

例如,将扩展名设为“.pdf”

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

你的意思是:

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)

您还可以使用表单中的clean()方法来验证它。因此,您可以拒绝不是mp3的文件。像这样的:

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

相关问题 更多 >