form表单上传文件
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),
url(r‘^upload_file/$‘,views.upload_file),
]
views.py
from django.shortcuts import render,HttpResponse,redirect
from app01 import models
from django.http import JsonResponse #这个模块就是向前端返回json格式数据
# Create your views here.
def index(request):
return render(request,‘index.html‘)
def upload_file(request):
‘‘‘form表单的文件上传‘‘‘
# file是一个文件对象
file = request.FILES.get(‘myfile‘) #这个FILES就是指发送过来的所有的文件,是一个字典形式
files = r‘D:\%s‘%file.name
# 保存该文件对象
with open(files,‘wb‘)as f:
for line in file:
f.write(line)
return HttpResponse(‘文件上传成功‘)
index.html
{#导入css用link#}
{#导入js用script#}
我是index页面#errors {
color: red;
margin: 0 0 0 10px;
}
form表单实现文件上传
{#form 表单上传文件一定要指定method的什么请求,然后enctye要指定格式 #}
Ajax 实现上传文件
PS:用Jquery获取文件,需要这样写,$(‘#myfile‘)就是根据id的名字获取到框架,$(‘#myfile‘)[0]就是取到原生的doom,$(‘#myfile‘)[0].files就会取到这个框内的所有文件(有可能是多个文件),$(‘#myfile‘)[0].files[0]这个取第0个就是我当前传的文件