Python文件上传功能简单实现

本文章代码上传在码云上

代码地址

git@gitee.com:DanYuJie/upanddown.git

这里我们使用flask框架,简单实用

目录结构:
upandown/static/css/js/jquery.min.jstoastr.min.jstemplates/index.htmltest.py    

首先我们需要一个页面在templates/index.html(这里使用form表单实现)

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><link rel="stylesheet" href="../static/css/toastr.min.css"><script src="../static/js/jquery.min.js"></script><script src="../static/js/toastr.min.js"></script><title>Document</title>
</head>
<body><form method="POST" action="/upload" enctype="multipart/form-data"><input type="file" name="file" id="file"><input type="submit" value="upload"><a href=""></a></form><hr><ol id="filelist"></ol><script>function checkstatus(){if('{{status}}'== 'OK'){toastr['success']("上传成功");}else if('{{status}}'== 'null'){toastr['error']("上传失败");           }}function get_list(){$.ajax({url:'/getlist',type:'GET',success:function(result){len_result = result.length;for(var x =0; x < len_result; x++){$("#filelist").append('<br><a href=/download/' + result[x] + '>' + result[x] +'</a>');}alert(content_list);},error:function(){alert("失败");}});}checkstatus();get_list();</script>
</body>
</html>

然后是后台接收

test.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Flask,render_template, request, send_from_directory,jsonify, redirect
import os
# import sys
# reload(sys)
# sys.setdefaultencoding('utf-8')
app = Flask(__name__)# ALLOWED_EXTENSTIONS = set(['png', 'jpg', 'jpeg', 'gif'])
app.config['UPLOAD_FOLDER'] = os.getcwd()
download_floder = app.config['UPLOAD_FOLDER'] + '/upload'def allow_file(filename):allow_list = ['png', 'PNG', 'jpg', 'doc', 'docx', 'txt', 'pdf', 'PDF', 'xls', 'rar', 'exe', 'md', 'zip'] a = filename.split('.')[1]if a in allow_list:return Trueelse:return False@app.route('/main')
def home():return render_template('index.html')@app.route('/getlist')
def getlist():file_url_list = []file_floder = app.config['UPLOAD_FOLDER'] + '/upload'file_list = os.listdir(file_floder)for filename in file_list:file_url = url_for('download',filename=filename)file_url_list.append(file_url)# print file_listreturn jsonify(file_list)@app.route('/download/<filename>')
def download(filename):return send_from_directory(download_floder,filename, as_attachment=True)@app.route('/upload', methods=['POST', 'GET'])
def upload():file = request.files['file']if not file:return render_template('index.html', status='null')# print type(file)if allow_file(file.filename):file.save(os.path.join(app.config['UPLOAD_FOLDER']+'/upload/', file.filename))return render_template('index.html', status='OK')else:return 'NO'if __name__ == '__main__':app.run(debug=True, host='0.0.0.0')

 



作者:LanceAdd
链接:https://www.jianshu.com/p/fbcd1760cae0
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/399838.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Arduino 端口通信实例

// //Arduino 1.0.x-----Arduino Uno----COM9 //使用3-10号引脚连接8个LED // int incomingByte 0; //输入的数据存储变量 int count1; void setup() {Serial.begin(9600);// opens serial port, sets data rate to 9600 bpsfor(int i3;i<10;i)//打开3-10号引脚pinMode(i…

redhat6.4 安装oracle 10g error

环境&#xff1a;操作系统:redhat6.4 64位数据库版本:10.2.0.4 64位搭建测试原因&#xff1a;http://718693.blog.51cto.com/708693/1682945说明&#xff1a;在redhat6.4上安装10.2.0.1 64位接着再升级到10.2.0.4 64位&#xff0c;在执行DBCA报如下错误UnsatisfiedLinkError ex…

sha256---利用java自带的实现加密

利用java自带的实现加密&#xff1a;参考https://jingyan.baidu.com/article/2fb0ba40a2ef2b00f3ec5f74.html /*** 利用java原生的摘要实现SHA256加密* param str 加密后的报文* return*/public static String getSHA256StrJava(String str){MessageDigest messageDigest;Stri…

Flask文件上传

https://zhuanlan.zhihu.com/p/23731819 Flask文件上传&#xff08;一&#xff09;&#xff1a;原生实现 李辉 greyli.com 87 人赞同了该文章 文件上传是个躲不掉的问题&#xff0c;用户头像&#xff0c;文章图片&#xff0c;文件分享等等都需要上传功能。但这里涉及很多内…

Python匿名函数——lambda表达式

如果要定义的函数很简单&#xff0c;一个return语句就能搞定&#xff0c;可以使用lambda表达式来定义&#xff0c; lambda表达式的语法如下&#xff1a; lambda parameters: expressionlambda表达式并不包含return语句&#xff0c;凡是使用函数作为参数或返回值的地方&#xff…

jQuery实现radio第一次点击选中第二次点击取消功能(转)

转载自&#xff1a;http://www.jb51.net/article/113730.htm 由于项目的需求&#xff0c;要求radio点击两次后为取消状态&#xff0c;不方便修改为checkbox&#xff0c;可以用正面的方法实现。 // jquery$(input:radio).click(function(){//alert(this.checked);//var $radio …

简单编码

将一串文本译成密码&#xff0c;密码的规律是&#xff1a; 将原来的小写字母全部翻译成大写字母&#xff0c;大写字母全部翻译成小写字母&#xff0c;数字的翻译规律如下&#xff1a; 0——>9 1——>8 2——>7 3——>6 4——>5 5——>4 6——>3 7——>…

QCon上海2015热点前瞻:Uber伸缩之道、注重实效的性能

QCon上海2015将于10月15日~17日举行。8月16日前报名&#xff0c;可享受8折优惠。\\本次大会设计了15个热点技术专题&#xff0c;涵盖大数据、架构、移动开发、产品设计、安全、团队建设、技术创业等热点话题。我们将邀请业界知名专家&#xff0c;分享他们的实践经验。目前已经确…

工具配置链接

一、idea运行eclipse和myeclipse项目 二、idea中git的使用 三、idea快捷键 转载于:https://www.cnblogs.com/javabeginer/p/7515071.html

C 文件读写 容易疏忽的一个问题

今天需要解决一个问题&#xff0c;将影像瓦片&#xff08;一堆jpg文件&#xff09;分别进行读取&#xff0c;并将所有数据以文件流的方式存入一个.db的文件中&#xff0c; 同时将每个jpg数据在db文件中的位置保存下来&#xff0c;作为index存在.idx文件中。 其中部分代码如下&a…

LNMP里常见的502问题

讲关于nginx的高级配置&#xff0c;在Apache讲了很多关于“用户认证”、“日志”、“重定向”等等操作&#xff0c;当然nginx也会有相同的操作。首先&#xff0c;我们把Discuz在Nginx下实现访问&#xff0c;用之前的域名www.test.com进入目录[rootLampLinux vhosts]# cd /usr/l…

python学习过程中随手写的测试脚本-testloop.py

## 定义list数组lstrs [t1,t2,t3,t4]print(lstrs is,lstrs) i 0## test for loopfor lstr in lstrs: print(lstrs[%d] is % i,lstr ) i i 1print(end for loop) j 0## test while loopwhile j < 3: print(lstrs[%d] is % j,lstrs[j] ) j j 1print(end while loop) k …

jQuery以JSONP的访问调用一个WCF REST服务

JSONP&#xff08;JSON with Padding&#xff09;可以看成是JSON的一种“使用模式”&#xff0c;用以解决“跨域访问”的问题. 下面是一个简单的例子用于模拟如何通过jQuery以JSONP的访问调用一个WCF REST服务。 在这个例子中&#xff0c;我们将定义一个用于返回所有员工信息的…

使用python将excel数据导入数据库

https://www.cnblogs.com/longbigbeard/p/9309180.html 因为需要对数据处理&#xff0c;将excel数据导入到数据库&#xff0c;记录一下过程。使用到的库&#xff1a;xlrd 和 pymysql &#xff08;如果需要写到excel可以使用xlwt&#xff09;直接丢代码&#xff0c;使用python…

imageDownloader

.h #import <UIKit/UIKit.h> protocol imageDownloadDelegate <NSObject> optional -(void)imageDownloadWithImage:(UIImage *)image; end // 声明一个block 参数类型是UIImage 返回值是void 别名Result typedef void(^Result)(UIImage *img); interface ImageDow…

Android核心分析之二十七Android GDI 之SurfaceFlinger之动态结构示

SurfaceFlinger对象建立过程示意  1 SurfaceSession的建立  客户端请求建立Surface时&#xff0c;首先在要与SurfaceFlinger建立一个Session&#xff0c;然后再Session上建立一个Connection通过概念返回Bclient对象。WindowManagerService在添加第一个窗口前会检查SurfaceS…

maven详解之坐标与依赖

2019独角兽企业重金招聘Python工程师标准>>> 看着简单而又复杂的pom.xml文件&#xff0c;看似熟悉&#xff0c;当自己编写的时候觉得简单&#xff0c;但是看人家项目的时候又觉得复杂的很&#xff0c;现在我们一起来分析这个pom文件。 Maven的坐标为各种构件引入了秩…

修改数据表部分字段方法封装-及-动态生成对象并动态添加属性

代码&#xff1a; //这样写的话&#xff0c;输入的是表的行对象&#xff0c;返回的是数据字典&#xff0c;可以直接用到更新操作里&#xff0c;public static Object AlterDate(Object tabledataobj){List<string> namelist new List<string>();List<Object>…

flask 上传 excel 并导入mysql

参考&#xff1a; flask 文件的上传下载和excel操作 Python 将Excel表格数据导入MySQL数据库

各种无线加密方式

所有的无线网络都提供某些形式的加密。但无线路由器、无线AP、或中继器的无线信号范围很难控制得准确&#xff0c;外界也是很大机会的能访问到该无线网络&#xff0c;一旦他们能访问该内部网络时&#xff0c;该网络中所有是传输的数据对他们来说都是透明的。如果这些数据都没经…