首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django提供未压缩的file.tar.gz

Django提供未压缩的file.tar.gz
EN

Stack Overflow用户
提问于 2016-06-07 10:25:41
回答 2查看 812关注 0票数 0

我想提供一些file.tar.gz服务,但是当我下载它时,文件不会被压缩。

我的应用程序正在运行的服务器上的文件有63 438字节:

代码语言:javascript
复制
-rw-r--r-- 1 root root 63448 Nov  5 14:13 file.tar.gz

但是当我下载它时,它有716800字节。

这是我的下载功能:

代码语言:javascript
复制
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

我想我打开文件的方式有问题,我只是找不到正确的解决方案。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-06-07 12:39:51

正如Klaus .在评论中所说,这是编码方面的一个问题。

当我改变

代码语言:javascript
复制
if encoding is not None:
    response['Content-Encoding'] = encoding

代码语言:javascript
复制
response['Content-Encoding'] = 'tar'

所有声明都能正常工作。

票数 0
EN

Stack Overflow用户

发布于 2021-04-14 11:41:21

如果您需要提供一个tar.gz文件,请这样做,

代码语言:javascript
复制
    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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37676767

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档