Django之文件上传


#示例一
#
views def upload(request): if request.method == "GET": return render(request, "upload.html") elif request.method == "POST": name = request.POST.get("user") img = request.FILES.get("img") print("用户名", name) print("文件名", img.name) print("文件大小", img.size) f = open(img.name, "wb") for line in img.chunks(): f.write(line) f.close() return HttpResponse("...") # 前端 <!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"> <input type="text" name="user"> <input type="file" name="img"> <input type="submit" value="提交"> </form> </body> </html>

 示例二:( form组件)

from django.shortcuts import render
from django.shortcuts import 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']
       
        # img是对象(文件大小,文件名称,文件内容。。。)
        print(img.name)
        print(img.size)
        f = open(img.name,'wb')
        for line in img.chunks():
            f.write(line)
        f.close()
        return HttpResponse('...')

 

posted @ 2017-03-20 14:42  LaniLai  阅读(200)  评论(0编辑  收藏  举报