码迷,mamicode.com
首页 > Web开发 > 详细

Django(十七)Ajax全套

时间:2019-04-10 23:39:15      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:end   基于   logs   title   col   osi   rect   type   HERE   

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")

 

Django(十七)Ajax全套

标签:end   基于   logs   title   col   osi   rect   type   HERE   

原文地址:https://www.cnblogs.com/xiangtingshen/p/10686712.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!