Django(十七)文件上传

http://www.cnblogs.com/wupeiqi/articles/5703697.html


    - 文件上传
        - 普通上传
        - 自定义页面上传按钮
        - 基于Form做上传
        - Ajax上传文件?????

一,上传文件

from django.shortcuts import render,redirect, HttpResponse

# Create your views here.

def update(request):
    if request.method == 'GET':
        return render(request, 'update.html')
    else:
        username = request.POST.get('username')
        img = request.FILES.get('img')
        print(img)
        print(username)
        file_name = img.name
        file_size = img.size
        print(file_name, file_size)
        f = open(img.name, 'wb')
        for line in img.chunks():
            f.write(line)
        f.close()


        return HttpResponse("ok")
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="/update/" method="post" enctype="multipart/form-data">
    {% csrf_token %}

    <input type="text" name="username">
    <div style="position: relative">
        <a href="">上传</a>
       <input type="file" name="img" style="opacity:0; position: absolute;left: 0;top: 0;">
    </div>

    <input type="submit" value="提交" />
</form>

</body>
</html>

基于Form上传

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="/update/" method="post" enctype="multipart/form-data">
    {% csrf_token %}

    {{ obj.user }}
    {{ obj.img }}

    <input type="submit" value="提交" />
</form>

</body>
</html>
from django.shortcuts import render,redirect, HttpResponse

# Create your views here.
from django import  forms
from django.forms import fields
class Upload(forms.Form):
    user = fields.CharField()
    img = fields.FileField()

def update(request):
    if request.method == 'GET':
        obj = Upload()
        return render(request, 'update.html',{'obj':obj})
    else:
        obj = Upload(request.POST, request.FILES)
        if obj.is_valid():
            username = obj.cleaned_data['user']
            img = obj.cleaned_data['img']
            print(img)
            print(username)
            file_name = img.name
            file_size = img.size
            print(file_name, file_size)
            f = open(img.name, 'wb')
            for line in img.chunks():
                f.write(line)
            f.close()


        return HttpResponse("ok")

 

posted @ 2019-04-10 22:40  狂奔~  阅读(133)  评论(0编辑  收藏  举报