Python学习总结:Django【高级篇】(二)
文件上传
前端页面内容
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>文件上传</title> </head> <body> <form method="POST" action="/upload/" enctype="multipart/form-data"> <input type="text" name="user" /> <input type="file" name="img"/> <input type="submit"/> </form> </body> </html>
后端程序实现
from django.shortcuts import render import os # Create your views here. def upload(request): if request.method == 'POST': # 判断页面请求的方式 user = request.POST.get('user') # 获取页面上传的input内容 # img = request.POST.get('img') img = request.FILES.get('img') # 获取上传的文件 img 对应html页面上的input框中name=img的信息 f = open(os.path.join('static/images', img.name), 'wb') # os.path.join 字符串拼接 wb 二进制写 使用w报错 for chunk in img.chunks(): # img.chunks是整个文件的全部内容,每次上传 f.write(chunk) f.close() print(user, img) print("http://127.0.0.1:8080/static/images/%s" % img.name) # 获取文件访问路径 return render(request, 'upload.html')
结果检查

验证码+session功能实现
出处:http://www.cnblogs.com/madsnotes/
声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。

浙公网安备 33010602011771号