Django下载文件无效

dan*_*ana 2 forms django file download

我正在尝试在用户的计算机上创建用于下载上载文件的脚本.问题是下载根本不起作用(它要么下载我一个空文件,要么给我一些错误).

最后一个错误是:强制转换为Unicode:需要字符串或缓冲区,找到FieldFile

def download_course(request, id):
    course = Courses.objects.get(pk = id).course

    path_to_file = 'root/cFolder'
    filename = course # Select your file here.                                
    wrapper = FileWrapper(file(course))
    content_type = mimetypes.guess_type(filename)[0]
    response = HttpResponse(wrapper, content_type = content_type)
    response['Content-Length'] = os.path.getsize(filename)
    response['Content-Disposition'] = 'attachment; filename=%s/' % smart_str(course)

    return response
Run Code Online (Sandbox Code Playgroud)

如何正确声明文件名,以便每次都知道要下载的文件:文件名实际上是'course',如上所述

谢谢 !

cji*_*cji 5

编辑

我认为你需要path从FileField对象中提取值:

def download_course(request, id):
    course = Courses.objects.get(pk = id).course

    path = course.path # Get file path
    wrapper = FileWrapper( open( path, "r" ) )
    content_type = mimetypes.guess_type( path )[0]

    response = HttpResponse(wrapper, content_type = content_type)
    response['Content-Length'] = os.path.getsize( path ) # not FileField instance
    response['Content-Disposition'] = 'attachment; filename=%s/' % \ 
                                       smart_str( os.path.basename( path ) ) # same here

    return response
Run Code Online (Sandbox Code Playgroud)

这是为什么:

假设我有(好吧,我实际上)模型:

class DanePracodawcy( DaneAdresowe, DaneKontaktowe ):
    # other fields
    logo = ImageWithThumbnailsField( upload_to = 'upload/logos/',
                                  thumbnail = {'size': (180, 90)},
                                  blank = True )
Run Code Online (Sandbox Code Playgroud)

ImageWithThumbnailsField是FileField的子类,因此它的行为方式相同.现在,当我做SELECT时:

mysql> select logo from accounts_danepracodawcy;
+-----------------------------+
| logo                        |
+-----------------------------+
| upload/logos/Lighthouse.jpg |
+-----------------------------+
1 row in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)

它显示(相对于MEDIA_ROOT)存储文件的路径.但是当我访问logoModel属性时:

[D:projekty/pracus]|1> from accounts.models import DanePracodawcy
[D:projekty/pracus]|4> DanePracodawcy.objects.get().logo
                   <4> <ImageWithThumbnailsFieldFile: upload/logos/Lighthouse.jpg>
[D:projekty/pracus]|5> type( _ )
                   <5> <class 'sorl.thumbnail.fields.ImageWithThumbnailsFieldFile'>
Run Code Online (Sandbox Code Playgroud)

我得到一些对象的实例.如果我尝试将该实例传递给os.path.getsize:

[D:projekty/pracus]|8> import os.path
[D:projekty/pracus]|9> os.path.getsize( DanePracodawcy.objects.get().logo )
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

D:\projekty\pracus\<ipython console> in <module>()

C:\Python26\lib\genericpath.pyc in getsize(filename)
     47 def getsize(filename):
     48     """Return the size of a file, reported by os.stat()."""
---> 49     return os.stat(filename).st_size
     50
     51

TypeError: coercing to Unicode: need string or buffer, ImageWithThumbnailsFieldFile found
Run Code Online (Sandbox Code Playgroud)

我和你一样得到TypeError.所以我需要文件路径作为字符串,可以使用path属性获得:

[D:projekty/pracus]|13> os.path.getsize(  DanePracodawcy.objects.get().logo.path )
                   <13> 561276L
Run Code Online (Sandbox Code Playgroud)

或者,我可以通过MEDIA_ROOT设置获取name属性和os.path.join它:

[D:projekty/pracus]|11> from django.conf import settings
[D:projekty/pracus]|12> os.path.getsize(  os.path.join( settings.MEDIA_ROOT, DanePracodawcy.objects.get().logo.name ) )
                   <12> 561276L
Run Code Online (Sandbox Code Playgroud)

但这是不必要的打字.

最后要注意的事项:因为path是绝对路径,我需要提取文件名以将其传递给Content-Disposition标头:

[D:projekty/pracus]|16> DanePracodawcy.objects.get().logo.path
                   <16> u'd:\\projekty\\pracus\\site_media\\upload\\logos\\lighthouse.jpg'
[D:projekty/pracus]|17> os.path.basename( DanePracodawcy.objects.get().logo.path )
                   <17> u'lighthouse.jpg'
Run Code Online (Sandbox Code Playgroud)