首页 > 编程语言 > 详细

python_django_上传文件

时间:2019-11-30 11:32:32      阅读:65      评论:0      收藏:0      [点我收藏+]

存储路径:

  • 存储在服务器的项目的static/upfile(你说了算的文件名,但是一般俺们叫这个)文件中

配置:

  • 配置settings.py文件
  • MDEIA_ROOT = os.path.join(BASE_DIR,r‘static\upfile‘) # 注:在windows下为‘\‘,linux为‘/‘,# static\upfile为上传文件目录

举个栗子:

对应的views.py文件

import os
from django.conf import settings
def savefile(request):
    if request.method == "POST":
        f = request.FILES[file]     #文件上传时,文件数据存储在request.FILES属性中
        # 文件在服务端的路径(本地服务器的路径)
        file = os.path.join(settings.MDEIA_ROOT,f.name)
        with open(filePath,wb) as fp:   # 若是图片文件则用wb二进制形式打开,若为普通文本文件则可以用b打开
            for info in f.chunks():   # 以文件流的形式一段一段的接收
                fp.write(info)
        return HttpResponse(上传成功)
    else:
        return HttpResponse(上传失败)

对应的url.py文件

    url(rupfile/$,views.upfile),
    url(rsavefile/$,views.savefile),

对应的html文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传文件</title>
</head>
<body>
<form method="post" action="/savefile/" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="submit" value="上传"/>
</form>
</body>
</html>

注:form表单要上传文件需要加enctype=‘multipart/form-data‘ 属性,method方法必须是post请求,

 

python_django_上传文件

原文:https://www.cnblogs.com/Vera-y/p/11961717.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!