Django下载文件不工作 [英] Django download file not working

查看:204
本文介绍了Django下载文件不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用户的机器上制作一个脚本来下载上传的文件。问题是,下载根本不起作用(它会下载我一个空文件,或给我一些错误)。



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

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

path_to_file ='root / cFolder'
filename = course#在此选择您的文件。
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

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



谢谢

解决方案

编辑



认为您需要从FileField对象中提取路径值:

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

path = course.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
pre>

为什么:



让我们说(好吧,我实际上有)型号: p>

  class DanePracodawcy(DaneAdresowe,DaneKontaktowe):
#其他字段
logo = ImageWithThumbnailsField(upload_to ='upload /标志/',
thumbnail = {'size':(180,90)},
blank = True)

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

  mysql>从accounts_danepracodawcy中选择徽标; 
+ ----------------------------- +
|标志|
+ ----------------------------- +
| upload / logos / Lighthouse.jpg |
+ ----------------------------- +
1行集(0.00秒)

它显示(相对于MEDIA_ROOT)存储文件的路径。但是当我访问 logo 模型属性:

  [D:projekty / pracus] | 1>来自accounts.models import DanePracodawcy 
[D:projekty / pracus] | 4> DanePracodawcy.objects.get()。logo
< 4> < ImageWithThumbnailsFieldFile:upload / logos / Lighthouse.jpg>
[D:projekty / pracus] | 5>类型(_)
< 5> < class'sorl.thumbnail.fields.ImageWithThumbnailsFieldFile'>

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

  [D:projekty / pracus] | 8是氢。 import os.path 
[D:projekty / pracus] | 9> os.path.getsize(DanePracodawcy.objects.get()。logo)
------------------------------ ---------------------------------------------
TypeError追溯(最近的最后一次呼叫)

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

C:\Python26\lib\genericpath.pyc in getsize(filename)
47 def getsize(filename):
48 返回os.stat()报告的文件大小。
---> 49 return os.stat(filename).st_size
50
51

TypeError:强制为Unicode:需要字符串或缓冲区,ImageWithThumbnailsFieldFile找到

我像你一样得到TypeError。所以我需要文件路径作为字符串,这可以通过路径属性获得:

  [D:projekty / pracus] | 13取代; os.path.getsize(DanePracodawcy.objects.get()。logo.path)
< 13> 561276L

或者,我可以得到名称属性和 os.path.join 它与MEDIA_ROOT设置:

  [D :projekty / pracus] | 11 GT;从django.conf导入设置
[D:projekty / pracus] | 12> os.path.getsize(os.path.join(settings.MEDIA_ROOT,DanePracodawcy.objects.get()。logo.name))
< 12> 561276L

但这是不必要的打字。



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

  [D:projekty / pracus] | 16取代; DanePracodawcy.objects.get()。logo.path 
< 16>你是:\\projekty\\prackus\\\\\\\\\upload\\logos\\\\lighthouse.jpg'
[D:projekty / pracus] | 17> ; os.path.basename(DanePracodawcy.objects.get()。logo.path)
< 17> u'lighthouse.jpg'


I'm trying to make a script for downloading the uploaded files, on the user's machine. The problem is that the download simply doesn't work (it either downloads me an empty file, or gives me some errors).

the last error is: coercing to Unicode: need string or buffer, FieldFile found

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

how can I declare properly the filename so that it will know each time what file to be downloading: the filename is actually 'course' as declared above

Thanks !

解决方案

edited

I think that you need to extract path value from FileField object:

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

Why is that:

Let's say I have (well, I actually have) Model:

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

ImageWithThumbnailsField is subclass of FileField, so it behaves the same way. Now, when I do SELECT:

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

it shows (relative to MEDIA_ROOT) path of stored file. But when I access logo Model attribute:

[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'>

I get instance of some object. If I try to pass that instance to 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

I get TypeError, like you. So I need file path as string, which can be obtained with path attribute:

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

Alternatively, I could get name attribute and os.path.join it with MEDIA_ROOT setting:

[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

But that's unnecessary typing.

Last thing to note: because path is absolute path, I need to extract filename to pass it to Content-Disposition header:

[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'

这篇关于Django下载文件不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆