[英]gzip.open(“file.tar.gz”, “rb”) vs. tarfile.open(“file.tar.gz”); extractall()
[英]Django serves file.tar.gz not compressed
我已經創建了提供一些 file.tar.gz 的視圖,但是當我下載它時,該文件沒有被壓縮。
運行我的應用程序的服務器上的文件有 63 438 字節:
-rw-r--r-- 1 root root 63448 Nov 5 14:13 file.tar.gz
但是當我下載它時它有 716 800 字節。
這是我的下載功能:
def download_logs(request):
""" View returning file to download """
file_path = request.GET['filepath']
original_filename = file_path.split("/")[-1]
try:
file_loaded = open(file_path, 'rb')
except IOError as err:
LOG.debug(err)
LOG.debug("File %s does not exist", file_path)
return error_view(request, "IOError", "File no longer exists.")
response = HttpResponse(file_loaded.read(), 'application/x-gzip')
file_loaded.close()
file_type, encoding = mimetypes.guess_type(original_filename)
if file_type is None:
file_type = 'application/octet-stream'
response['Content-Type'] = file_type
response['Content-Length'] = str(os.stat(file_path).st_size)
if encoding is not None:
response['Content-Encoding'] = encoding
# To inspect details for the below code, see http://greenbytes.de/tech/tc2231/
if u'WebKit' in request.META['HTTP_USER_AGENT']:
# Safari 3.0 and Chrome 2.0 accepts UTF-8 encoded string directly.
filename_header = 'filename=%s' % original_filename.encode('utf-8')
elif u'MSIE' in request.META['HTTP_USER_AGENT']:
# IE does not support internationalized filename at all.
# It can only recognize internationalized URL, so we do the trick via routing rules.
filename_header = ''
else:
# For others like Firefox, we follow RFC2231 (encoding extension in HTTP headers).
filename_header = 'filename*=UTF-8\'\'%s' % urllib.quote(original_filename.encode('utf-8'))
response['Content-Disposition'] = 'attachment; ' + filename_header
return response
我認為我打開文件的方式有問題,我只是找不到正確的解決方案。
如果您需要提供 tar.gz 文件,請執行此操作,
tar = tarfile.open("file_name.tar.gz", "r")
response = HttpResponse(tar, content_type='application/tar+gzip')
response['Content-Disposition'] = 'attachment; filename="file_name.tar.gz"'
return response
正如 Klaus D. 在評論中所說,這是編碼問題。
當我改變
if encoding is not None:
response['Content-Encoding'] = encoding
到
response['Content-Encoding'] = 'tar'
一切都表明工作正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.