django 下載文件,指定文件中文名稱

 

Content-disposition 是 MIME 協議的擴展,MIME 協議指示 MIME 用戶代理如何顯示附加的文件。
Content-disposition其實能夠控制用戶請求所得的內容存爲一個文件的時候提供一個默認的文件名,文件直接在瀏覽器上顯示或者在訪問時彈出文件下載對話框。
Content-Disposition就是當用戶想把請求所得的內容存爲一個文件的時候提供一個默認的文件名。django

 

import os,sys
from django.http import StreamingHttpResponse
from django.utils.encoding import escape_uri_path


def file_iterator(file_name, chunk_size=512):
        with open(file_name,'rb') as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

def extractfile(request):
    filepath="/".join(os.path.dirname(os.path.abspath(__file__)).split("/")[:-1])+"/files"
    the_file_name = filepath+"/Kafka權威指南.pdf"
    response = StreamingHttpResponse(file_iterator(the_file_name))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename="{0}"'.format(escape_uri_path('Kafka權威指南.pdf'))

    return response

 

 

參考;segmentfault

https://segmentfault.com/q/1010000009078463瀏覽器

https://www.jianshu.com/p/4c52cb691f54app

https://cloud.tencent.com/developer/article/1365795spa

相關文章
相關標籤/搜索