Ajax+Python flask实现上传文件功能
HTML:
<div >
<input type="file" name="FileUpload" id="FileUpload">
<a class="layui-btn layui-btn-mini" id="btn_uploadimg">上传图片</a>
</div>
Ajax实现:
<script type="text/jscript">
$(function () {
$("#btn_uploadimg").click(function () {
var fileObj = document.getElementById("FileUpload").files[0]; // js 获取文件对象
if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
alert("请选择图片");
return;
}
var formFile = new FormData();
formFile.append("action", "UploadVMKImagePath");
formFile.append("file", fileObj); //加入文件对象
//第一种 XMLHttpRequest 对象
//var xhr = new XMLHttpRequest();
//xhr.open("post", "/Admin/Ajax/VMKHandler.ashx", true);
//xhr.onload = function () {
// alert("上传完成!");
//};
//xhr.send(formFile);
//第二种 ajax 提交
var data = formFile;
$.ajax({
url: "/upload/",
data: data,
type: "Post",
dataType: "json",
cache: false,//上传文件无需缓存
processData: false,//用于对data参数进行序列化处理 这里必须false
contentType: false, //必须
success: function (result) {
alert("上传完成!");
},
})
})
})
</script>
后台flask:
from flask import Flask,render_template,request,redirect,url_for
from werkzeug.utils import secure_filename
import os
from flask import send_from_directory
from werkzeug import SharedDataMiddleware UPLOAD_FOLDER = '/uploads' #文件存放路径
ALLOWED_EXTENSIONS = set(['jpg']) #限制上传文件格式 app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/upload/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit an empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return '{"filename":"%s"}' % filename
return ''
以上基本上就可以实现上传功能了。
以下是对界面样式,就是选择文件的那个上传按钮样式做了一些修改
如下图:

HTML:此处还添加了文件格式限制,只能选择 .torrent 文件
<div class="divcenter" style="width:1025px">
<div style="width:100%;height:600px">
<div id="div_torrent" style="overflow:hidden">
<a id="btn_file" href="javascript:;" class="file" style="margin-top:5px;margin-bottom:5px;float:left;">选择文件
<input type="file" name="FileUpload" id="FileUpload" accept=".torrent">
</a>
<div id="showFileName" style="float:left;margin-top:7px;margin-bottom:5px;"></div>
<input id="btn_upload" type="button" value="上传" onclick="onsubmit" class="file" style="float:right;width:65px; height: 33px;left: 4px;background-color:rgba(255, 206, 68, 0.6);cursor:hand;margin-top:5px;margin-bottom:5px;margin-right:5px;border-color:red" />
</div>
</div>
</div>
CSS样式:
.file {
position: relative;
display: inline-block;
background: #D0EEFF;
border: 1px solid #99D3F5;
border-radius: 4px;
padding: 4px 12px;
overflow: hidden;
color: #1E88C7;
text-decoration: none;
text-indent:;
line-height: 20px;
}
.file input {
position: absolute;
font-size: 100px;
right:;
top:;
opacity:;
}
.file:hover {
background: #AADFFD;
border-color: #78C3F3;
color: #004974;
text-decoration: none;
}
以上代码选择文件后,不会显示文件名,所以需要添加一个事件:
<script type="text/jscript">
$(function () {
$("#btn_file").on("change","input[type='file']",function(){
var filePath=$(this).val();
if(filePath.indexOf("torrent")!=-1){
var arr=filePath.split('\\');
var fileName=arr[arr.length-1];
$("#showFileName").html(fileName); }else{
$("#showFileName").html("");
}
})
})
</script>
上传的代码没做修改:此处增加了一个最大文件大小限制 5Mb
<script type="text/jscript">
$(function () {
$("#btn_upload").click(function () {
var fileObj = document.getElementById("FileUpload").files[0]; // js 获取文件对象
if (typeof (fileObj) == "undefined" || fileObj.size <= 0|| $("#showFileName").html()=="") {
alert("请选择BT种子");
return;
}if(fileObj.size>5242880)
{
alert("BT种子限制最大 5Mb");
return;
}
var formFile = new FormData();
formFile.append("action", "UploadTorrentPath");
formFile.append("file", fileObj); //加入文件对象
//第一种 XMLHttpRequest 对象
//var xhr = new XMLHttpRequest();
//xhr.open("post", "/Admin/Ajax/VMKHandler.ashx", true);
//xhr.onload = function () {
// alert("上传完成!");
//};
//xhr.send(formFile);
//第二种 ajax 提交
var data = formFile;
$.ajax({
url: "/upload/",
data: data,
type: "Post",
dataType: "json",
cache: false,//上传文件无需缓存
processData: false,//用于对data参数进行序列化处理 这里必须false
contentType: false, //必须
success: function (result) {
alert("上传完成!");
},
error: function (xmlrequest, textStatus, errorThrown) {
alert("上传失败!");
//alert("error:" + textStatus + errorThrown + ":" + JSON.stringify(xmlrequest));
console.log("error:" + textStatus + errorThrown + ":" + JSON.stringify(xmlrequest));
}
})
})
})
</script>
PS.喜欢看动漫的同学,可以来我的网站下载动漫哦 www.wikibt.com
参考文章1:https://www.cnblogs.com/LoveTX/p/7081515.html
参考文章2:https://www.haorooms.com/post/css_input_uploadmh
Ajax+Python flask实现上传文件功能的更多相关文章
- jQuery+php+ajax实现无刷新上传文件功能
jQuery+php+ajax实现无刷新上传文件功能,还带有上传进度条动画效果,支持图片.视频等大文件上传. js代码 <script type='text/javascript' src='j ...
- Python基于Python实现批量上传文件或目录到不同的Linux服务器
基于Python实现批量上传文件或目录到不同的Linux服务器 by:授客 QQ:1033553122 实现功能 1 测试环境 1 使用方法 1 1. 编辑配置文件conf/rootpath_fo ...
- flask控制上传文件的大小
1.flask控制上传文件的大小的方案是全局控制:http://docs.jinkan.org/docs/flask/patterns/fileuploads.html from flask impo ...
- egg.js 通过 form 和 ajax 两种方式上传文件并自定义目录和文件名
egg.js 通过 form 和 ajax 两种方式上传文件并自定义目录和文件名 评论:10 · 阅读:8437· 喜欢:0 一.需求 二.CSRF 校验 三.通过 form 表单上传文件 四.通过 ...
- Flask使用bootstrap为HttpServer添加上传文件功能
关于模态框 使用bootstrap实现点击按钮弹出窗口,简直不要太简单.我们只需要将写好的窗口内容隐藏,然后调用bootstrap的框架即可,简单几行就能完成相关功能实现.... 前提条件是,我们需要 ...
- 巨蟒python全栈开发django11:ajax&&form表单上传文件contentType
回顾: 什么是异步? 可以开出一个线程,我发出请求,不用等待返回,可以做其他事情. 什么是同步? 同步就是,我发送出了一个请求,需要等待返回给我信息,我才可以操作其他事情. 局部刷新是什么? 通过jq ...
- 【python】用python脚本Paramiko实现远程执行命令、下载、推送/上传文件功能
Paramiko: paramiko模块,基于SSH用于连接远程服务器并执行相关操作. SSHClient: 用于连接远程服务器并执行基本命令 SFTPClient: 用于连接远程服务器并执行上传下载 ...
- Python+Selenium学习--上传文件
场景 文件上传操作也比较常见功能之一,上传功能操作webdriver 并没有提供对应的方法,关键上传文件的思路.上传过程一般要打开一个系统的window 窗口,从窗口选择本地文件添加.所以,一般会卡在 ...
- $Django ajax简介 ajax简单数据交互,上传文件(form-data格式数据),Json数据格式交互
一.ajax 1 什么是ajax:异步的JavaScript和xml,跟后台交互,都用json 2 ajax干啥用的?前后端做数据交互: 3 之前学的跟后台做交互的方式: -第一种:在浏览器 ...
随机推荐
- 【开源GPS追踪】 之 服务器硬伤
前面就说过了,目前GPS 追踪的原理都是通过GPRS将数据发送到一个服务器上,如果回看数据就从服务器上去数据,服务器在整个系统中具有举足轻重的地位. 如果服务器坏了,整个系统几千台设备可能也就无法工作 ...
- Docker安装管理界面portainer
在Ubuntu或者Debian已经部署完毕Docker 拉取镜像文件: sudo docker pull docker.io/portainer/portainer Using default tag ...
- 【树形dp入门】没有上司的舞会 @洛谷P1352
传送门 题目描述 某大学有N个职员,编号为1~N.他们之间有从属关系,也就是说他们的关系就像一棵以校长为根的树,父结点就是子结点的直接上司.现在有个周年庆宴会,宴会每邀请来一个职员都会增加一定的快乐指 ...
- Deepin 15.4 编译安装 LNMP(PHP 5.6.31 + Nginx 1.12.1 + MySQL 5.6.36)
先查看先前的文章:Ubuntu 14 编译安装 PHP 5.4.45 + Nginx 1.4.7 + MySQL 5.6.26 笔记 编译 Nginx #安装依赖库 sudo apt-get -y i ...
- 枚举进行位运算 枚举组合z
枚举进行位运算--枚举组合 public enum MyEnum { MyEnum1 = , //0x1 MyEnum2 = << , //0x2 MyEnum3 = << , ...
- Ubuntu远程连接MySQL(connection refused)解决方法
一.判断ubuntu是否开启防火墙 sudo ufw status 开放防火墙3306端口 sudo ufw allow 3306 二.查看3306端口是否打开 注意:红色框框表示3306绑定的ip ...
- jQuery Distpicker插件 省市区三级联动 动态赋值修改地址
在获取创建页面数据后需要在编辑页面调取之前提交的数据,在使用这个插件后发现无法动态赋值,查找资料后发现需要先销毁实例,$(’#target’).distpicker(‘destroy’); 第一步 引 ...
- echarts中tooltip提示框位置控制
关键代码: position: function(point, params, dom, rect, size) { //其中point为当前鼠标的位置,size中有两个属性:viewSize和con ...
- h264_rtp打包解包类及实现demo
打包头文件: class CH2642Rtp { public: CH2642Rtp(uint32_t ssrc, uint8_t payloadType = 96, uint8_t fps = 25 ...
- iOS10使用SecKeyCreateWithData读取公钥私钥
在使用openssl命令生成RSA公钥私钥以后,当后端人员把密钥的字符串发给你: 首先要问清公钥私钥的密钥格式(PKCS1,PKCS8),密钥位数(1024,2048),然后在iOS10以后,使用苹果 ...