<!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进行文件上传并获取上传进度案例的更多相关文章

  1. Python+Django+js+echarts引入本地js文件的操作方法

    1. 选择正确的echarts.js,开发版选择echarts.baidu.com上的源码版,避免出现问题 2. 在项目主目录中新建static文件夹,里面建立js.css.images文件夹 3. ...

  2. [Python] Django框架入门5——静态文件、中间件、上传图片和分页

    说明: 本文主要描述Django其他的内容,涉及静态文件处理.中间件.上传文件.分页等. 开发环境:win10.Python3.5.Django1.10. 一.静态文件处理 在Django项目的静态文 ...

  3. 原生js实现ajax的文件异步提交功能、图片预览功能.实例

    采用html5使得选择图片改变时,预览框中图片随之改变.input文件选择框美化.原生js完成文件异步提交 效果图: 代码如下,可直接复制并保存为html文件打开查看效果 <html> & ...

  4. struts2文件上传时获取上传文件的大小

    利用struts2框架上传文件时,如果想要获取上传文件的大小可以利用下面的方式进行: FileInputStream ins = new FileInputStream(file); if (ins. ...

  5. js之Ajax下载文件

    传统上,客户端将依靠浏览器来处理从服务器下载文件.然而,这种方法需要打开一个新的浏览器窗口,iframe或任何其他类型的不友好和黑客行为.为下载请求添加额外的头信息也很困难.更好的解决方案是使用HTM ...

  6. python django url直接访问txt文件。urls.py路由直接指向txt文件

    from django.views.generic import TemplateView urlpatterns = [ url(r'^test/',TemplateView.as_view(tem ...

  7. python 通过js控制滚动条拉取全文 通过psutil获取pid窗口句柄,通过win32gui使程序窗口前置 通过autopy实现右键菜单和另存为操作

    1.参考 利用 Python + Selenium 自动化快速截图 利用 Python + Selenium 实现对页面的指定元素截图(可截长图元素) 使用python获取系统所有进程PID以及进程名 ...

  8. tp5 ajax单文件上传

    HTML代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="U ...

  9. [Python] Django框架入门

    说明:Django框架入门 当前项目环境:python3.5.django-1.11 项目名:test1 应用名:booktest 命令可简写为:python manager.py xxx => ...

随机推荐

  1. VMware ESXI6.0服务器安装

    1.制作一个ESXI6.0的系统安装盘 2.服务器启动后加载VMware ESXi 6.0的ISO文件,开始安装. 3.ESXi引导装入程序,VMware ESXi引导过程,在屏幕上方显示的版本号.内 ...

  2. [iOS]@synthesize和@dynamic关键字

    首先讲@property, 这是iOS6以后出来的关键词. 用它声明一个属性之后, 编译器会自动给你生成setter和getter方法的声明以及实现还有一个以_xxx 的成员变量(xxx是你属性定义的 ...

  3. 高并发数据库之MySql性能优化实战总结

    向MySQL发送一个请求时MySQL具体的操作过程 慢查询 1.慢查询 SHOW VARIABLES LIKE '%quer%' 索引优化技巧 1.对于创建的多列索引(复合)索引,只要查询条件使用了最 ...

  4. HDU 4508 湫湫系列故事——减肥记I (完全背包)

    题意:有n种食物,每种食物可以给湫湫带来一个幸福感a,同时也会给她带来b的卡路里的摄入,然后规定她一天摄入的卡路里的量不能超过m,一共有n种食物,问可以得到的 最大的幸福感是多少? 解题报告:一开始以 ...

  5. linux怎么执行jar文件 怎么打可执行的jar包

    Linux下执行jar文件方法:命令行下进入文件目录,执行java -jar file.jar即可,也可在桌面创建一个启动器,在命令栏填写相关的命令:java -jar /file路径/file.ja ...

  6. 云计算-MapReduce

    Hadoop示例程序WordCount详解及实例http://blog.csdn.net/xw13106209/article/details/6116323 hadoop中使用MapReduce编程 ...

  7. 【Alsa】播放声音和录音详细流程

    linux中,无论是oss还是alsa体系,录音和放音的数据流必须分析清楚.先分析alsa驱动层,然后关联到alsa库层和应用层. 二,链接分析: 1)链路一 usr/src/linux-source ...

  8. Gitlab & Github

    windwos上Git的使用 软件下载地址:https://github.com/git-for-windows/git/releases/download/v2.15.1.windows.2/Git ...

  9. jquery.validate动态更改校验规则

    有时候表单中有多个字段是相互关联的,以下遇到的就是证件类型和证件号码的关联,在下拉框中选择不同的证件类型,证件号码的值的格式都是不同的,这就需要动态的改变校验规则. 点击(此处)折叠或打开 <! ...

  10. vue里面使用Velocity.js

    英文文档:http://velocityjs.org/ https://github.com/julianshapiro/velocity 中文手册(教程):http://www.mrfront.co ...