Skip to content

Commit

Permalink
download files
Browse files Browse the repository at this point in the history
  • Loading branch information
joknarf committed Dec 12, 2024
1 parent bdf256b commit 8750a8b
Showing 1 changed file with 25 additions and 18 deletions.
43 changes: 25 additions & 18 deletions pywebfs/pywebfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -561,20 +561,29 @@ def list_directory(self, path):
self.write_html(f'<p id="info">{nbfiles} file{s} - {" ".join(convert_size(size))}</p>')

def download(self, path):
tmpdir = os.path.expanduser("~/.pywebfs")
basedir = os.path.basename(path.rstrip("/"))
tmpzip = tmpdir + "/" + basedir
make_archive(tmpzip, 'zip', "." + path)
tmpzip += ".zip"
fstat = os.stat(tmpzip)
self.send_response(HTTPStatus.OK)
self.send_header("Content-type", "application/zip")
self.send_header("Content-Length", str(fstat[6]))
self.send_header("Content-Disposition", f'attachment; filename="{basedir}.zip"')
super().end_headers()
with open(tmpzip, 'rb') as f:
self.copyfile(f, self.wfile)
os.remove(tmpzip)
if os.path.isdir(path):
tmpdir = os.path.expanduser("~/.pywebfs")
basedir = os.path.basename(path.rstrip("/"))
tmpzip = tmpdir + "/" + basedir
make_archive(tmpzip, 'zip', path)
tmpzip += ".zip"
fstat = os.stat(tmpzip)
self.send_response(HTTPStatus.OK)
self.send_header("Content-type", "application/zip")
self.send_header("Content-Length", str(fstat[6]))
self.send_header("Content-Disposition", f'attachment; filename="{basedir}.zip"')
super().end_headers()
with open(tmpzip, 'rb') as f:
self.copyfile(f, self.wfile)
os.remove(tmpzip)
elif os.path.isfile(path):
self.send_response(HTTPStatus.OK)
self.send_header("Content-Type", self.guess_type(self.path))
self.send_header("Content-Length", os.stat(path).st_size)
self.send_header("Content-Disposition", 'attachment')
super().end_headers()
with open(path, 'rb') as f:
self.copyfile(f, self.wfile)

def do_HEAD(self):
self.send_response(HTTPStatus.OK)
Expand Down Expand Up @@ -626,10 +635,10 @@ def do_GET(self):
searchtxt = q.get("searchtxt", [""])[0]
download = q.get("download", [""])[0]
path = displaypath = fs_path(p.path)
if download:
return self.download("."+path)
if not os.path.isdir("."+path):
return super().do_GET()
if download:
return self.download(path)
title = f"{self.server.title} - {html.escape(path, quote=False)}"
htmldoc = HTML
htmldoc += f"<title>{title}</title>\n</head>"
Expand Down Expand Up @@ -662,8 +671,6 @@ def do_GET(self):

self.write_html(htmldoc)



if p.query:
if searchtxt:
self.search_files(search, "." + path)
Expand Down

0 comments on commit 8750a8b

Please sign in to comment.