下载返回损坏的文件(瓶子+ pymongo)?

时间:2014-02-18 19:16:16

标签: python mongodb python-3.x bottle gridfs

我在'/ add'上有一个基本的网络表单,它接受用户输入并上传到mongodb:

PYTHON:

@bottle.route('/add')
def add_page():
    return bottle.template('files_test/add')

@bottle.route('/upload', method='POST')
def do_upload():
    data = request.files.data
    if data:
        raw = data.file.read()  # This is dangerous for big files
        file_name = data.filename
        try:
            newfile_id = fs.put(raw, filename=file_name)
        except:
            return "error inserting new file"
    print(newfile_id)
    return bottle.redirect('/')

add.tpl:

<!DOCTYPE html>

<!-- pass in files (dict)-->
<html>
<head>
    <title>Preformance and Capacity Management</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="file" name="data" /><br>
    <input type="submit"/>
</form>
</body>
</html>

我有一个显示数据的页面,并下载它:

PYTHON:

@bottle.route('/download')
def download():
    file_id = ObjectId(bottle.request.query.id)
    if file_id:
        try:
            file_to_download = fs.get(file_id)
        except:
            return "document id not found for id:" + file_id, sys.exc_info()[0]
        file_extension = str(file_to_download.name)[(str(file_to_download.name).index('.')):]


        response.headers['Content-Type'] = (mimetypes.types_map[file_extension])
        response.headers['Content-Disposition'] = 'attachment; filename=' + file_to_download.name

home.tpl:

<body>

<br><br><br><br>
%for fileobj in files:
    Filename: {{fileobj['filename']}}<br>
    Size: {{fileobj['length']}}<br>
    Date Uploaded: {{fileobj['uploadDate']}}<br>
    md5: {{fileobj['md5']}}<br>
    <a href="download?id={{fileobj['_id']}}">&lt--Download File--&gt</a>
<br><br><br><br>
%end
</body>

当我尝试下载文件时,会下载它们,但我无法打开它们。例如,内部带有“test”字样的文本文件将打开空白。 excel电子表格打开已损坏。

我上传或下载错误了吗?或两者?有关完整代码,请参阅代码审核上的this post

1 个答案:

答案 0 :(得分:1)

将以下行添加到“download”功能中的“server.py”文件中:

return file_to_download

我需要设置HTTP标头,然后返回原始数据。