微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

23ajax实现上传文件的功能

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个就是我当前传的文件

分享图片

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐