文件上传及数据保存

文件上传及数据保存

通过form表单和 Ajax 形式上传文件

1.urls.py路由配置

from django.conf.urls import url
from django.contrib import admin
from app01 import views


urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
]

2.模板index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script>
    <script src="https://cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
</head>
<body>

<form action="/index/" method="post" enctype="multipart/form-data">    {# 发送图片是需要enctype="multipart/form-data" 参数  #}
    {% csrf_token %}
    <p><input type="text" name="user" id="user"></p>
    <p><input type="file" name="file" id="file"></p>
    <input type="submit">
</form>
<input type="button" value="ajax提交" id="buttn">

<script>
    $("#buttn").click(function () {
        // 实例化一个对象 使用 new FormData()
        var formdata=new FormData();
        formdata.append("username",$("#user").val());          // username 为 key ,$("#user").val() 为值;将键值对追加到 formdata中
        formdata.append("imgFile",$("#file")[0].files[0]);     // 获取的 二进制文件

        $.ajax({
            url:"/index/",
            headers:{"X-CSRFToken":$.cookie('csrftoken')},
            type:"POST",
            data:formdata,
            processData:false,      // 数据是否做预处理    (传文件时需要设置)
            contentType:false,      // 编码类型          (传文件时需要设置)
            success:function (data) {
                console.log(data)
            }
        })
    })
</script>
</body>
</html>

3.views.py 视图函数

from django.shortcuts import render,HttpResponse,redirect

# Create your views here.
def index(request):
    if request.is_ajax():
        print("====", request.POST)         # 获取提交的  数据内容
        print(request.FILES)                     # 获取提交的  文件内容

        file_obj = request.FILES.get("imgFile")   # imgFile 是在模板中 的 key
        with open(file_obj.name,"wb") as f:         # 打开一个文件将 拿到的 file_obj 写入到该文件中
            for line in file_obj:
                f.write(line)
        return HttpResponse("Ajax")

    # 通过form 表单的形式传送文件
    if request.method=="POST":
        # request.POST.get
        print(request.POST)
        print(request.FILES)       # 图片传送过来会放在 该方法中 Files

        file_obj = request.FILES.get("imgFile")
        print(file_obj.name)        # file_obj.name 用来获取文件的名字

        with open(file_obj.name,"wb") as f:         # 打开一个文件将 拿到的 file_obj 写入到该文件中
            for line in file_obj:
                f.write(line)

        return HttpResponse("OK")
    return render(request,"index.html")
posted @ 2017-12-13 12:51  叨客厨子  阅读(291)  评论(0编辑  收藏  举报