python django + js 使用ajax进行文件上传并获取上传进度案例
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#progress{
height:10px;
width:500px;
border: 1px solid gold;
position: relative;
border-radius: 5px;
}
#progress .progress-item{
height:100%;
position: absolute;
left:0;
top:0;
background: chartreuse;
border-radius: 5px;
transition: width .3s linear;
}
</style>
</head>
<body>
<p style="color: blue;">上传文件:<br></p>
<input type="file" id="file"><br>
<p style="color: blue;">文件上传进度:<br></p>
<div id="progress">
<div class="progress-item"></div>
</div>
<p style="color: blue;">文件上传状态:<br></p>
<span id="callback" style="color: red;"></span>
</body>
<script>
//首先监听input框的变动,选中一个新的文件会触发change事件
document.querySelector("#file").addEventListener("change",function () {
//获取到选中的文件
var file = document.querySelector("#file").files[0];
//创建formdata对象
var formdata = new FormData();
formdata.append("file",file); // 后台接收"file"字段
//创建xhr,使用ajax进行文件上传
var xhr = new XMLHttpRequest();
xhr.open("post","/system/upload/");
//回调
xhr.onreadystatechange = function () {
if (xhr.status==200){
document.querySelector("#callback").innerText = xhr.responseText;
}else{
}
}
//获取上传的进度
xhr.upload.onprogress = function (event) {
if(event.lengthComputable){
var percent = event.loaded/event.total *100;
document.querySelector("#progress .progress-item").style.width = percent+"%";
}
}
//将formdata上传
xhr.send(formdata);
});
</script>
</html>
后端代码
def upload_files(request):
if request.method == 'POST':
try:
get_file = request.FILES.get('file')
if get_file is not None:
# print type(get_file) # <class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
# print get_file.read()
for con in get_file.readlines():
line = con.strip("\n")
if line.startswith("#"):
pass
else:
print line
return HttpResponse("success!")
else:
print u"文件对象是None"
return HttpResponse("false!")
except Exception, e:
print e
return HttpResponse("false!")
后面的几种方法没试:
方式一:
通过form表单提交到后台
前端:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/upload/" method="post" enctype="multipart/form-data">
<input type="file" name="fafafa">
<input type="submit">
</form>
</body>
</html>
Django 后端:
def upload(request):
if request.method == 'POST':# 获取对象
obj = request.FILES.get('fafafa')
import os
# 上传文件的文件名
print(obj.name) f = open(os.path.join(BASE_DIR, 'static', 'pic', obj.name), 'wb')
for chunk in obj.chunks():
f.write(chunk)
f.close()
return HttpResponse('OK')
return render(request, 'upload/upload.html')
方式二:
通过ajax提交
前端
<div>
<input type="file" name="file" id="file_upload">
<input type="button" value="上传" onclick="FileUpload()">
</div>
JS:
<script src="/static/js/jquery-3.2.1.min.js"></script>
<script>
function FileUpload() {
var form_data = new FormData();
var file_info =$( '#file_upload')[0].files[0];
form_data.append('file',file_info);
//if(file_info==undefined)暂且不许要判断是否有附件
//alert('你没有选择任何文件');
//return false
$.ajax({
url:'/upload_ajax/',
type:'POST',
data: form_data,
processData: false, // tell jquery not to process the data
contentType: false, // tell jquery not to set contentType
success: function(callback) {
console.log('ok')
}
});
}</script>
Django 后端:
def upload_ajax(request):
if request.method == 'POST':
file_obj = request.FILES.get('file')
import os
f = open(os.path.join(BASE_DIR, 'static', 'pic', file_obj.name), 'wb')
print(file_obj,type(file_obj))
for chunk in file_obj.chunks():
f.write(chunk)
f.close()
print('11111')
return HttpResponse('OK')
注意:
前台发送ajax请求时:
processData: false, // tell jquery not to process the data
contentType: false, // tell jquery not to set contentType
必须设置
方式三:
通过iframe标签提交
前端:
<div>
<form id="my_form" name="form" action="/upload_iframe/" method="POST" enctype="multipart/form-data">
<input type="text" name="user">
<input type="password" name="password">
<input type="file" name="file">
<input type="button" value="upload" onclick="UploadFile()">
</form>
<iframe id='my_iframe' name='my_iframe' src="" class="hide"></iframe>
</div>
JS:
function UploadFile() {
document.getElementById('my_iframe').onload = Testt;
document.getElementById('my_form').target = 'my_iframe';
document.getElementById('my_form').submit();
}
function Testt(ths){
var t = $("#my_iframe").contents().find("body").text();
console.log(t);
}
Django 后端:
def upload_iframe(request):
if request.method == 'POST':
print(request.POST.get('user', None))
print(request.POST.get('password', None))
file_obj = request.FILES.get('file')
import os
f = open(os.path.join(BASE_DIR, 'static', 'pic', file_obj.name), 'wb')
print(file_obj,type(file_obj))
for chunk in file_obj.chunks():
f.write(chunk)
f.close()
print('11111')
return HttpResponse('OK')
以上是文件上传的三种方式,在Tornado种也可以使用。
扩展:
在前段提交的时候 可以存在 checkbox 标签, 在Django中对于这种标签在后台获取值时用:
request.POST.getlist('favor', None) checkbox
其它
request.POST.get('favor', None) checkbox
python django + js 使用ajax进行文件上传并获取上传进度案例的更多相关文章
- Python+Django+js+echarts引入本地js文件的操作方法
1. 选择正确的echarts.js,开发版选择echarts.baidu.com上的源码版,避免出现问题 2. 在项目主目录中新建static文件夹,里面建立js.css.images文件夹 3. ...
- [Python] Django框架入门5——静态文件、中间件、上传图片和分页
说明: 本文主要描述Django其他的内容,涉及静态文件处理.中间件.上传文件.分页等. 开发环境:win10.Python3.5.Django1.10. 一.静态文件处理 在Django项目的静态文 ...
- 原生js实现ajax的文件异步提交功能、图片预览功能.实例
采用html5使得选择图片改变时,预览框中图片随之改变.input文件选择框美化.原生js完成文件异步提交 效果图: 代码如下,可直接复制并保存为html文件打开查看效果 <html> & ...
- struts2文件上传时获取上传文件的大小
利用struts2框架上传文件时,如果想要获取上传文件的大小可以利用下面的方式进行: FileInputStream ins = new FileInputStream(file); if (ins. ...
- js之Ajax下载文件
传统上,客户端将依靠浏览器来处理从服务器下载文件.然而,这种方法需要打开一个新的浏览器窗口,iframe或任何其他类型的不友好和黑客行为.为下载请求添加额外的头信息也很困难.更好的解决方案是使用HTM ...
- python django url直接访问txt文件。urls.py路由直接指向txt文件
from django.views.generic import TemplateView urlpatterns = [ url(r'^test/',TemplateView.as_view(tem ...
- python 通过js控制滚动条拉取全文 通过psutil获取pid窗口句柄,通过win32gui使程序窗口前置 通过autopy实现右键菜单和另存为操作
1.参考 利用 Python + Selenium 自动化快速截图 利用 Python + Selenium 实现对页面的指定元素截图(可截长图元素) 使用python获取系统所有进程PID以及进程名 ...
- tp5 ajax单文件上传
HTML代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="U ...
- [Python] Django框架入门
说明:Django框架入门 当前项目环境:python3.5.django-1.11 项目名:test1 应用名:booktest 命令可简写为:python manager.py xxx => ...
随机推荐
- Ansible Role
Ansible Role 专题总揽 https://www.jianshu.com/p/1be92c3f65ec lework 关注 2017.03.02 12:57* 字数 629 阅读 1439评 ...
- Java基础-SSM之mybatis一对一关联
Java基础-SSM之mybatis一对一关联 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.准备测试环境(创建数据库表) 1>.创建husbands和wifes表并建 ...
- log4j2常见配置
依赖jar: <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId> ...
- S折交叉验证(S-fold cross validation)
S折交叉验证(S-fold cross validation) 觉得有用的话,欢迎一起讨论相互学习~Follow Me 仅为个人观点,欢迎讨论 参考文献 https://blog.csdn.net/a ...
- IO 复习字节流字符流拷贝文件
/* 本地文件 URL 文件拷贝 *//*文本文件拷贝 可以通过 字符流,也可以通过字节流*/ /*二进制文件拷贝 只可以通过字节流*//* 希望这个例子能帮助搞懂 字符流与字节流的区别 */ imp ...
- Myeclipse 工具优化 [内存一直增加, jsp,javascript 编辑很卡]
首先看这篇随笔 地址: Myeclipse/STS 首次在本地部署配置一个Spring MVC 项目 (十二) [http://www.cnblogs.com/editor/p/3915239.htm ...
- F - Friends ZOJ - 3710(暴力)
题目链接:https://cn.vjudge.net/contest/280949#problem/F 题目大意:给你n个人,然后给你m个关系,每个关系输入t1, t2 .代表t1和t2是朋友关系(双 ...
- Linux内核启动流程分析(一)【转】
转自:http://blog.chinaunix.net/uid-25909619-id-3380535.html 很久以前分析的,一直在电脑的一个角落,今天发现贴出来和大家分享下.由于是word直接 ...
- cancel_delayed_work和flush_scheduled_work【转】
转自:http://blog.chinaunix.net/uid-9688646-id-4052595.html 是不是觉得很玄?像思念一样玄?那好,我们来看点具体的,比如935行,INIT_DELA ...
- nginx tomcat 自动部署python脚本【转】
#!/usr/bin/env python #--coding:utf8-- import sys,subprocess,os,datetime,paramiko,re local_path='/ho ...