加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

(23)ajax实现上传文件的功能

发布时间:2020-12-16 02:57:31 所属栏目:百科 来源:网络整理
导读: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

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

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
{#导入css用link#}
<link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/bootstrap-3.3.7-dist/css/bootstrap.css">
{#导入js用script#}
<script src="/static/jquery-3.3.1.js"></script>
<title>我是index页面</title>
<style>
#errors {
color: red;
margin: 0 0 0 10px;
}
</style>
</head>
<body>
<h1>form表单实现文件上传</h1>
{#form 表单上传文件一定要指定method的什么请求,然后enctye要指定格式 #}
<form action="/upload_file/" method="post" enctype="multipart/form-data">
<input type="file" name="myfile">
<input type="submit" value="上传文件">
</form>
</body>
</html>

?

Ajax 实现上传文件

PS:用Jquery获取文件,需要这样写,$(‘#myfile‘)就是根据id的名字获取到框架,$(‘#myfile‘)[0]就是取到原生的doom,$(‘#myfile‘)[0].files就会取到这个框内的所有文件(有可能是多个文件),$(‘#myfile‘)[0].files[0]这个取第0个就是我当前传的文件

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读