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

前端实现


"zh-CN">

    "UTF-8">
    "X-UA-Compatible" content="IE=edge">
    "viewport" content="width=device-width, initial-scale=1">
    上传文件
    




基于form表单的上传文件

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

"text" name="user">

"file" name="f">

"submit">

基于ajax上传文件

{ % csrf_token %}

"text" id="user">

"file" id="f">

index.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')
Views.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'^put_ajax/', views.put_ajax),
    url(r'^index/', views.index),
]
url.py

 

图示:

Django 基于Ajax & form 简单实现文件上传_第1张图片

上传前:

Django 基于Ajax & form 简单实现文件上传_第2张图片

进行上传:

Django 基于Ajax & form 简单实现文件上传_第3张图片

Django 基于Ajax & form 简单实现文件上传_第4张图片

上传后:

Django 基于Ajax & form 简单实现文件上传_第5张图片

 

转载于:https://www.cnblogs.com/bigtreei/p/8427108.html

你可能感兴趣的:(python,javascript,前端)