Django's small note FileResponse implements file download

I learned FileResponse today. This module is amazing. After learning it, I have begun to imagine what I will be like in the front-end in the future, and I am drooling just thinking about it.

FileResponse

FileResponse is a subclass of StreamingHttpResponse with automatic segmentation and automatic iteration, suitable for binary file transmission. Commonly used transmission file formats include py, txt, jpg, png, gif, docx, xlsx, mp3, mp4, etc.

Let's take a look at the code.

from django.http import FileResponse

def download(request):
    response = FileResponse(open(r"yinyue.mp3", "rb"))
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = "attachment;filename=music.mp3"  # 注意filename不支持中文
    return response

Define the download function in the view, note that the request must be used as a parameter, and the FileResponse module needs to be imported. When using FileResponse to read a file, you can directly use the open function without using the with open method. There are two specific MIME tags Content-Type and Content-Disposition, the first is to specify the file type, the second is to specify the name of the file to download, note that there is an attachment parameter, and filename does not support Chinese names (for the time being I understand that).

Finally, if you use a relative path when specifying the file path, you should pay special attention. The relative path should be relative to manage.py, not relative to the view function.
insert image description here
Because MP3 and manage.py are in the same level directory, the direct reference is done. Oh by the way, when reading and writing, read and write in binary, which is rb, not r.

Guess you like

Origin blog.csdn.net/lishuaigell/article/details/124226453