Add the following line to the "server.py" file in the "download" function :
return file_to_download
I needed to set the HTTP headers and THEN return the raw data.
Question
I have a basic web form at '/add' that takes user input and uploads to a 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>
I have a page that displays the data, and downloads it:
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']}}"><--Download File--></a>
<br><br><br><br>
%end
</body>
When I try to download the files, it downloads them, but I cannot open them. For example, a text file with the words "test" inside will open up blank. An excel spreadsheet opens up corrupted.
Am I uploading or downloading wrong? or both? For full code, see this post on Code Review.
Solution
Add the following line to the "server.py" file in the "download" function :
return file_to_download
I needed to set the HTTP headers and THEN return the raw data.