django--文件上传
<form action="/upload.html/" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="user"> <div style="position: relative"> <a >上传</a> <input type="file" name="img" style="opacity:0.2;position: absolute;top:0;left:0;"> </div> <input type="submit" value="提交"> </form>
把上传标签透明为0,a标签覆盖在上传input标签,可以定义文字或样式
python 代码
from django.shortcuts import render,HttpResponse from django import forms from django.forms import fields class UploadForm(forms.Form): user = fields.CharField() img = fields.FileField() def upload(request): if request.method == 'GET': return render(request,'upload.html') else: # 方法一: #obj = UploadForm(request.POST,request.FILES) # if obj.is_valid(): # user = obj.cleaned_data['user'] # img = obj.cleaned_data['img'] #方法二: print(request.POST) print(request.FILES) # img是对象(文件大小,文件名称,文件内容…………) img = request.FILES.get('img') print(img.name) print(img.size) #把文件内容保存服务器 f=open(img.name,'wb') for line in img.chunks(): f.write(line) return HttpResponse('OK')
上班求生存,下班求发展