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


 

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

 

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

 

 

參考;

https://segmentfault.com/q/1010000009078463

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

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

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM