ahserver_g/ahserver/filedownload.py

53 lines
1.2 KiB
Python
Raw Normal View History

2019-08-28 11:46:31 +08:00
import os
import asyncio
2019-08-29 15:30:35 +08:00
import mimetypes
2019-08-28 11:46:31 +08:00
from aiohttp.web_exceptions import HTTPNotFound
from aiohttp.web import StreamResponse
from aiohttp import web
import aiofile
from appPublic.rc4 import RC4
crypto_aim = 'God bless USA and others'
def path_encode(path):
rc4 = RC4()
return rc4.encode(path,crypto_aim)
def path_decode(dpath):
rc4 = RC4()
return rc4.decode(dpath,crypto_aim)
2020-12-18 13:27:53 +08:00
async def file_download(request, filepath, content_type=None):
2019-08-28 11:46:31 +08:00
filename = os.path.basename(filepath)
2019-08-29 15:30:35 +08:00
r = web.FileResponse(filepath)
2020-12-18 13:27:53 +08:00
ct = content_type
if ct is None:
ct, encoding = mimetypes.guess_type(filepath)
2019-08-29 15:30:35 +08:00
if ct is not None:
r.content_type = ct
else:
r.content_type = 'application/octet-stream'
r.content_disposition = 'attachment; filename=%s' % filename
r.enable_compression()
return r
2019-08-28 11:46:31 +08:00
if os.path.exists(filepath):
2019-08-29 15:30:35 +08:00
length = os.path.getsize(filepath)
response = web.Response(
2019-08-28 11:46:31 +08:00
status=200,
2019-08-29 15:30:35 +08:00
headers = {
'Content-Disposition': 'attrachment;filename={}'.format(filename)
}
2019-08-28 11:46:31 +08:00
)
await response.prepare(request)
2019-08-29 15:30:35 +08:00
cnt = 0
with open(filepath, 'rb') as f:
chunk = f.read(10240000)
cnt = cnt + len(chunk)
await response.write(chunk)
await response.fsyn()
2019-08-28 11:46:31 +08:00
await response.write_eof()
return response
raise HTTPNotFound