Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在Django中获取文件的扩展名?_Python_Django_File Upload - Fatal编程技术网

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

Python 如何在Django中获取文件的扩展名?,python,django,file-upload,Python,Django,File Upload,我正在Django中构建一个web应用程序。 我有一个表单,它将文件发送到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(handl

我正在Django中构建一个web应用程序。 我有一个表单,它将文件发送到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中获取文件类型

谢谢

你的意思是:

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

使用
导入模拟类型,magic

mimetypes.MimeTypes().types_map_inv[1][
    magic.from_buffer(form.cleaned_data['file'].read(), mime=True)
][0]
例如,将扩展名设置为“.pdf”




获取直接请求:

import os


extesion = os.path.splitext(str(request.FILES['file_field']))[1]
或者在db-model中获取extesion

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]
使用图书馆

:

使用
MimeTypes().guess\u extension()
方法。检查下面的代码片段

# 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

您可以使用
request.FILES[“file\u field\u name”]。content\u type

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


…或
os.path.splitext(file)[1]
我得到了一个错误:“InMemoryUploadedFile”对象没有属性“split”,如果他要做的只是根据文件扩展名进行筛选,这实际上只是一个方便的功能(就这一点而言,有人可以轻松上传包含任何具有MP3文件扩展名的任意数据的文件,或不具有该文件扩展名的MP3文件),所以他可能应该在客户端进行操作,以减少请求大小。我希望Django中的扩展在服务器端进行筛选,而不是在客户端进行筛选。@MarcosAguayo handle_uploaded_song中存在冲突,请尝试将其放在handle_uploaded_song之前。您的“content_type”变量来自何处?只是想知道。抱歉,这是一个错误。谢谢您是从哪里获得docfile.name中的docfile的?这是一个错误,应该是文件,在前一行中正在检查。可能是复制粘贴错误,抱歉:)奇怪的是,这个答案被标记为正确-它只检查文件名,下面的答案与魔术数字检查是更好和安全的way@MarceioSoares从request.data猜测pdf扩展名时,这不起作用。@PranKumarSarkar您确定您使用的pdf文件工作正常吗?您使用的Python版本是什么?我刚刚试过在电脑中使用Python3.6.9版本和PDF文件,效果很好。Python3.7我并不是在猜测存储中的PDF文件扩展名。我试图从内存文件
request.data.get('filenamefield')
my_file = request.FILES["file_field_name"]
if my_file.content_type != 'text/csv':
    print("Your file must be a CSV type")