Django入门教程(八):文件上传和下载

大家好,我是连人。本期我们继续分享文件的上传和下载。

首先,在static中下创建一个新的文件夹file。
在这里插入图片描述
当然你也可以在与static和templates的同级下新建一个文件夹,但此时需要通过settings.py将这个文件夹注册成静态文件夹,方法和设置static一样。

接下来看views.py:

import os

from django.http import StreamingHttpResponse, Http404
from django.shortcuts import render, redirect

def upload(request):
    if request.method == 'POST':
        file = request.FILES.get("file", None)
        if not file:
            message = "no files for upload!"
            return render(request, 'file.html', locals())
        if not file.name.endswith(".jpg"):              # 检测是否为jpg,防止文件上传攻击
            message = "only JPG is accepted!"
            return render(request, 'file.html', locals())
        file.name = 'pic' + '.jpg'          # 再次改名,防止文件上传攻击
        if os.path.exists(file.name):
            os.remove(file.name)            # 如果存在该文件名的文件则移除
        destination = open(os.path.join("static/file", file.name), 'wb+')
        for chunk in file.chunks():
            destination.write(chunk)
        destination.close()
        message = "upload successfully!"
        return render(request, 'file.html', locals())
    return render(request, 'file.html')


def download(request):
    try:
        response = StreamingHttpResponse(open('static/file/pic.jpg', 'rb'))
        response['content_type'] = "application/octet-stream"
        response['Content-Disposition'] = 'attachment; filename=' + os.path.basename('static/file/pic.jpg')
        return response
    except Exception:
        raise Http404

file.html:

<!DOCTYPE html>
<html>
    <head>
        <title>file</title>

    </head>
    <body>

        <form action="/upload/" method="post" enctype="multipart/form-data"> <!-- 不要忘记写enctype -->
            {% csrf_token %}
                <input type="file" name="file"/>
                <button type="submit">提交</button>
        </form>
        <br/>
        <a href="../download/">download</a>
        <br/>
        <a href="../">back to home</a>
        <br/>
        <a href="../register/">go to register</a>
            {% if message %}
            <script type="text/javascript">
               alert("{{message}}");
            </script>
            {% endif %}
    </body>
</html>

本次分享就到这里。

转载注明出处。

发布了10 篇原创文章 · 获赞 1 · 访问量 729

猜你喜欢

转载自blog.csdn.net/mirocky/article/details/104003241