使用Flas下载从MongoDB检索的文件

2024-10-02 06:21:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建web应用程序,用于使用Flask向MongoDb上传和下载文件。首先,我将搜索MongoDb数据库(特别是集合)以查找匹配字符串,如果在任何文档中存在匹配字符串,那么我需要创建动态URL(可从搜索页面单击)以使用ObjectId进行下载。一旦我点击了动态URL,它就应该为那个特定的ObjectId检索存储在MongoDb中的文件并下载它。我尝试将response.headers['Content-Type']和{}更改为原始值,但由于某些原因,下载没有按预期工作。在

路径.py

@app.route('/download/<fileId>', methods = ['GET', 'POST'])
def download(fileId):
    connection = pymongo.MongoClient()

    #get a handle to the test database
    db = connection.test
    uploads = db.uploads

    try:
        query = {'_id': ObjectId(fileId)}
        cursor = uploads.find(query)

        for doc in cursor:
            fileName = doc['fileName']
            response = make_response(doc['binFile'])
            response.headers['Content-Type'] = doc['fileType']
            response.headers['Content-Dispostion'] = "attachment; filename="+fileName
            print response.headers

        return response
    except Exception as e:
        return render_template('Unsuccessful.html')

我应该怎么做才能下载文件(从MongoDB中按预期工作)使用与我先前上传的相同的文件名和数据?在

下面是最近运行的日志。在

enter image description here

从MongoDb检索到的文件(在本例中为“Big Data Workflows presentation 1.pptx”)是使用ObjectId文件名下载的,尽管我正在将文件名更改为原始文件名。在

enter image description here

如果我遗漏了任何细节,请告诉我。我会相应地更新帖子。在

提前谢谢你


Tags: 文件字符串urldoc文件名responsemongodbtype
1条回答
网友
1楼 · 发布于 2024-10-02 06:21:56

感谢@Bartek Jablonski的意见。在

最后,我对代码做了一些调整,并在MongoDB中创建了新的集合(我想这次我很幸运)。在

@app.route('/download/<fileId>', methods = ['GET', 'POST'])
def download(fileId):
    connection = pymongo.MongoClient()

    #get a handle to the nrdc database
    db = connection.nrdc
    uploads = db.uploads

    try:
        query = {'_id': ObjectId(fileId)}
        cursor = uploads.find(query)

        for doc in cursor:
            fileName = doc['fileName']
            response = make_response(doc['binFile'])
            response.headers['Content-Type'] = doc['fileType']
            response.headers["Content-Dispostion"] = "attachment; filename=\"%s\"" %fileName
        return response
    except Exception as e:
#          self.errorList.append("No results found." + type(e))
        return False

相关问题 更多 >

    热门问题