Django中ajax技术和form表单两种方式向后端提交文件

一、Form表单方式提交:
form表单提交文件或者图像时需要对form中的属性进行如下设置:
1、method="post" //提交方式 post
2、enctype="multipart/form-data" //不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。
3、action="/code/" //提交给哪个url

code.html文件





代码统计


{% csrf_token %}

url

url(r'code/$',views.code)

views.py

def code(request):
    if request.method == "POST":
        filename = request.FILES['file'].name
        with open(filename, 'wb') as f:
            for chunk in request.FILES['file'].chunks():
                f.write(chunk)
        return HttpResponse('上传成功')
    return render(request, 'code.html')

二、ajax方式提交文件:
直接上代码吧,代码有注释
code.html:




    
    代码统计


{% csrf_token %}

url:

  url(r'code/$',views.code)

views.py:

from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
def code(request):
    res={'code':0}
    if request.method == "POST":
        file_obj = request.FILES['file']
        filename = file_obj.name
        with open(filename, 'wb') as f:
            for chunk in file_obj.chunks():
                f.write(chunk)
        res['msg'] = '上传成功'
        return JsonResponse(res)
    return render(request, 'code.html')

你可能感兴趣的:(Django中ajax技术和form表单两种方式向后端提交文件)