python实现文件上传并返回进度_python django + js 使用ajax进行文件上传并获取上传进度案例...

本文介绍如何使用Python Django和JavaScript配合,通过Ajax实现文件上传并实时显示上传进度。包括前端HTML样式、JavaScript监听上传进度和后端Django接收文件的处理方法。同时提到了通过form表单、Ajax以及iframe三种上传方式,并强调了在Ajax请求中`processData`和`contentType`的设置重要性。
部署运行你感兴趣的模型镜像
Document

#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;

}

上传文件:

文件上传进度:

文件上传状态:

//首先监听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);

});

后端代码

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) #

# 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表单提交到后台

前端:

Title

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提交

前端

JS:

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')

}

});

}

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标签提交

前端:

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

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值