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 => ...
随机推荐
- Spring整合Quartz定时任务 在集群、分布式系统中的应用(Mysql数据库环境)
Spring整合Quartz定时任务 在集群.分布式系统中的应用(Mysql数据库环境) 转载:http://www.cnblogs.com/jiafuwei/p/6145280.html 单个Q ...
- 了解Linux操作系统的引导过程
原文地址:http://os.51cto.com/art/200706/49690.htm 1.简介 Linux启动过程指的是从加电到看到shell提示的这一段时间. Linux启动的过程可以大概分为 ...
- Why is my Spring @Autowired field null?
spring有@Autowired 空指针异常 https://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-fiel ...
- IDEA启动Tomcat报错1099 is already in use
IDEA中启动Tomcat报错,Error running Tomcat7.0.52: Address localhost:1099 is already in use 或者是 java.rmi.se ...
- 贪心算法: Codevs 1052 地鼠游戏
#include <iostream> #include <algorithm> #include <queue> #include <cstring> ...
- elementUI下拉框错误记录
选择广东省深圳市,保存,再编辑是这样效果 原因 保存的那张表相关字段为字符串,而生成下拉框该字段是整数,两者改成一致即可 修改后
- 【原创】when.js2.7.1源码解析
现在,用回调处理一些复杂的逻辑,显得代码臃肿,难于阅读,特别是异步,嵌套. 解决这样的问题,可以是之前所说的Backbone.Events的pubsub,或者是今天要说的when.js所实现的prom ...
- HDU 2159 FATE (二维背包)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2159 解题报告:这题实际上是一个二维的背包问题,也可以由01背包扩展而来,01背包用一维数组,可想而知 ...
- 叉积(POJ - 2318 )
题目链接:https://cn.vjudge.net/contest/276358#problem/A 题目大意:给你一个矩阵的左上角和右下角,然后n个竖杠,这n个竖杠将这个矩阵分成n+1个方块,给你 ...
- 字符串对象的charAt函数存在的意义
var style = ""; style[0] //undefined var style = ""; style.charAt(0); //"&q ...