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>
后端实现
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')
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), ]
图示:
上传前:
进行上传:
上传后: