Django 基于Ajax & form 简单实现文件上传

时间:2022-11-22 14:42:09

前端实现

Django 基于Ajax & form 简单实现文件上传Django 基于Ajax & form 简单实现文件上传
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>上传文件</title>
    <script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>


<h2>基于form表单的上传文件</h2>
<form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    <p><input type="text" name="user"></p>
    <p><input type="file" name="f"></p>
    <input type="submit">
</form>


<hr>
<h2>基于ajax上传文件</h2>
{% csrf_token %}
<p><input type="text" id="user"></p>
<p><input type="file" id="f"></p>
<button class="ajax_btn">上传</button>


<script>
    $(".ajax_btn").click(function () {
        var formdata = new FormData();
        formdata.append("user", $("#user").val());
        formdata.append("csrfmiddlewaretoken", $("[name='csrfmiddlewaretoken']").val());
        formdata.append("f", $("#f")[0].files[0]);
        $.ajax({
            url: "/put_ajax/",
            type: "post",
            data: formdata,
            contentType: false,
            processData: false,
            success: function (data) {
                alert("上传成功!")
            }
        })

    })
</script>

</body>
</html>
index.html

后端实现

Django 基于Ajax & form 简单实现文件上传Django 基于Ajax & form 简单实现文件上传
from django.shortcuts import render, HttpResponse

# Create your views here.


def index(request):
    if request.method == "POST":
        print(request.POST)
        print(request.FILES.get("f"))
        f_obj = request.FILES.get("f")
        name = f_obj.name
        f_write = open(name, "wb")
        for line in f_obj:
            f_write.write(line)
        return HttpResponse("上传成功")
    return render(request, 'index.html')


def put_ajax(request):
    if request.is_ajax():
        f_obj = request.FILES.get("f")
        print(f_obj)
        name = f_obj.name
        print(name)
        f_write = open(name, "wb")
        for line in f_obj:
            f_write.write(line)
        return HttpResponse("上传成功")
    return render(request, 'index.html')
Views.py
Django 基于Ajax & form 简单实现文件上传Django 基于Ajax & form 简单实现文件上传
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^put_ajax/', views.put_ajax),
    url(r'^index/', views.index),
]
url.py

 

图示:

Django 基于Ajax & form 简单实现文件上传

上传前:

Django 基于Ajax & form 简单实现文件上传

进行上传:

Django 基于Ajax & form 简单实现文件上传

Django 基于Ajax & form 简单实现文件上传

上传后:

Django 基于Ajax & form 简单实现文件上传