使用web2py返回uploads目录中的文件 - 字符串问题

时间:2011-06-22 11:44:13

标签: python web2py

我让用户使用数据库将文件上传到伪目录结构中。我有父路径的字段&文件名&我使用我的控制器设置的文件(文件类型为“upload”)。我可以看到文件正确存储在uploads目录中,以便正常工作。仅供参考,我使用

存储文件
db.allfiles.insert(filename=filename, \
    parentpath=parentpath, \
    file=db.allfiles.file.store(file.file,filename), \
    datecreated=now,user=me)

我正在尝试设置下载文件的功能,以便用户可以使用app / controller / function / myfiles / image.jpg等内容下载文件。我使用此代码找到该文件:

file=db((db.allfiles.parentpath==parentpath)&\
        (db.allfiles.filename==filename)&\
        (db.allfiles.user==me)).select()[0]

我尝试返回file.file,但文件我得到的jpg文件是字符串,如:

allfiles.file.89fe64038f1de7be.6d6f6e6b65792d372e6a7067.jpg

数据库中的文件名是什么。我试过这段代码:

os.path.join(request.folder,('uploads/'),'/'.join(file.file))

但我正在走这条道路:

/home/charles/web2py/applications/chips/uploads/a/l/l/f/i/l/e/s/./f/i/l/e/./8/9/f/e/6/4/0/3/8/f/1/d/e/7/b/e/./6/d/6/f/6/e/6/b/6/5/7/9/2/d/3/7/2/e/6/a/7/0/6/7/./j/p/g

我认为这是特殊类型的字符串或者file.file不完全是字符串。有什么东西我可以通过我的函数将文件返回给用户吗?

2 个答案:

答案 0 :(得分:4)

你几乎是对的。尝试:

os.path.join(request.folder,'uploads',file.file)

答案 1 :(得分:1)

Python字符串是序列类型,因此是可迭代的。当您将单个字符串作为参数提交给join方法时,它会迭代字符串中的每个字符。所以,例如:

>>> '/'.join('hello')
'h/e/l/l/o'

另请注意,os.path.join会自动将其参数与OS的相应路径分隔符(即os.path.sep)分开,因此无需手动插入斜杠。