<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <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;position:absolute;top:0;left: 0;" /> </div> <input type="submit" value="提交" /> </form> </body> </html>
视图函数代码
from django.shortcuts import render from django.shortcuts import HttpResponse from django import forms from django.forms import fields
---------------------- 上传表单的Form表单验证 ------------------------
class UploadForm(forms.Form): user = fields.CharField() img = fields.FileField()
---------------------- 上传表单的Form表单验证 ------------------------
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']
---------------------- 如果用form表单,可以省略下面这两行 ------------------------
# 如果上面没有用Form表单,使用下面两行,本代码是属于用Form表单形式 # 获取用户提交的普通字段 user = request.POST.get('user') # 获取用户提交的img文件 # 对应前端代码<input type="file" name="img"/> img = request.FILES.get('img')
---------------------- 如果用form表单,可以省略下面这两行 ------------------------
# img是对象(文件大小,文件名称,文件内容...) print(img.name) print(img.size) f = open(img.name,'wb') # chunks表示一块块的 for line in img.chunks(): f.write(line) f.close() return HttpResponse('...')