django上传文件简单实现

django上传文件是通过html中form标签实现,通过url.py路由寻址,views.py文件进行逻辑处理,保存在相对路径下

html大致格式:

1:entype="multipart/form-data"类型

2:input标签 type="file"

 后台文件接收:

url.py路由找到对应的函数处理关系

url(r"upload/$", views.upload)

 

文件传入是class类,查看打印的接收结果:

为了获取用户上传文件名称,我们需要获取文件name值,将文件放到指定的文件夹里,代码如下:

1:获取文件是通过request.FILES["upload_file"]或者request.FILES.get("upload_file",None)方式

2:获取文件夹位置,将文件保存到自己建立的路径下,upload_file.name获取名称

3.写入文件的时候可以使用upload_file.chunk()方法

def upload(request):
    if request.method == "POST":
        upload_file = request.FILES.get("upload_file")
        path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "statics")
        if upload_file:
            with open(os.path.join(path, upload_file.name), "wb") as f:
                for line in upload_file.readlines():
                    f.write(line)
        return HttpResponse("upload finish")
    return render(request, "upload.html")

大概思路是这样,敲代码思路 要清晰,知道一步步是怎么走的

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值