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>

本次分享就到这里。

转载注明出处。

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值