我正在使用Flask构建用于上传和下载MongoDb文件的Web应用程序。首先,我将在特定集合中搜索MongoDb数据库以匹配字符串,如果在任何文档中有匹配的字符串,那么我需要使用ObjectId创建动态URL(可从搜索页面点击)下载。一旦我点击动态URL,它应检索存储在MongoDb中的特定ObjectId文件并下载它。我尝试将response.headers['Content-Type']
和response.headers["Content-Dispostion"]
更改为原始值,但由于某种原因,下载无法按预期运行。
route.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中检索 - 按预期工作),其文件名和数据与我之前上传的相同?
以下是最近一次运行的日志。
即使我将文件名更改为原始文件名,从MongoDb检索的文件(在本例中为#34; Big Data Workflows presentation 1.pptx&#34;)也会使用ObjectId文件名下载。
如果我遗漏任何细节,请告诉我。我会相应更新帖子。
提前致谢,
答案 0 :(得分:0)
感谢@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