python flask解决上传下载的问题
记录瞬间
最近为了解决一些新的需求,简单介入了flask对文件的上传和下载的方法,并分别使用python和curl模拟发送
代码:
#! /usr/bin/env python3
# coding:utf-8
import platform from werkzeug.utils import secure_filename
from flask import Flask, jsonify, request, Response
import os app = Flask(__name__)
UPLOAD_FOLDER = 'upload'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 20 * 1024 * 1024 # 定义最大上传文件大小为:20M ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'xls', 'JPG', 'PNG', 'zip', 'gif', 'GIF'])
run_path = "./" # 根据不同的操作系统,定义基础运行路径
if platform.system() == "Linux":
run_path = r'/opt/AutoUpload/'
if platform.system() == "Windows":
run_path = r'D:/PythonWorkSpace/'
msg = 'niGEin!' # 用于判断文件后缀
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS # 上传文件-upload-file
@app.route('/uf', methods=['POST'], strict_slashes=False)
def api_upload():
file_dir = run_path + UPLOAD_FOLDER
if not os.path.exists(file_dir):
os.makedirs(file_dir)
f = request.files['file'] # 获取上传文件 print(request.values.get("filePath")) fname = secure_filename(f.filename)
ext = fname.rsplit('.', 1)[1] # 获取文件后缀 f.save(os.path.join(file_dir, fname)) # 保存文件到upload目录
if ext == 'zip':
pass
return jsonify({"errno": "", "errmsg": u"success"}) # 下载文件-download-file
@app.route('/df', methods=['GET', 'POST'])
def api_download():
if request.method == 'GET':
fullfilename = request.json['fileName']
print(fullfilename)
filepath = run_path + 'tools/' + fullfilename
print(filepath)
if not os.path.isfile(filepath):
print("nononononono!!!")
return
# 普通下载
# response = make_response(send_from_directory(filepath, fullfilename, as_attachment=True))
# response.headers["Content-Disposition"] = "attachment; filename={}".format(filepath.encode().decode('latin-1'))
# return response # 流式读取
def send_file():
store_path = filepath
with open(store_path, 'rb') as targetfile:
while 1:
data = targetfile.read(1 * 1024 * 1024) # 每次读取1M
if not data:
break
yield data response = Response(send_file(), content_type='application/octet-stream')
response.headers["Content-disposition"] = 'attachment; filename=%s' % fullfilename
return response if __name__ == '__main__':
app.run(debug=True, port=5002, host='0.0.0.0')
# 默认127.0.0.1:5000,这里修改了地址和端口方便自己使用
调用方式:
# coding:utf-8
import requests
from urllib3 import encode_multipart_formdata url = "http://localhost:5002/up"
data = {
"filePath": ""
}
header = {}
data['file'] = ("xx.zip", open(r"./basedir/xx.zip", 'rb').read())
encode_data = encode_multipart_formdata(data)
data = encode_data[0]
header['Content-Type'] = encode_data[1]
try:
result = requests.request(method='POST', url=url, headers=header, data=data, timeout=(3, 100)) if "true" in result.text:
analyse_json = result.json()
print("向服务器发送文件并解压成功")
result_path = analyse_json["data"]
print("服务器端的地址为 {}".format(result_path))
else:
print("向服务器发送文件并解压Failed {}".format(result.text))
except Exception as e:
print("执行发送数据失败.{}".format(e)) #-------------------------------------------- url = "http://localhost:5002/df"
data = {
"fileName": "xx.jar"
} result = requests.request(method="GET", url=url, json=data, stream=True)
f = open(data['fileName'], "wb")
for chunk in result.iter_content(chunk_size=512):
if chunk:
f.write(chunk) #---------------------------------------------
使用curl命令进行发送文件的方式:
curl ${URL} -X POST -F "file=@${app_path}/${APP_NAME}.zip" -F "ip1=${IP}" -F "ip2=${get_ip}" -F "port=${port}" -F "num=${num}"
python flask解决上传下载的问题的更多相关文章
- python day32--struct,文件上传下载
一.struct模块 可以把要发送的数据长度转换成固定长度的字节 struct.pack('i',数据长度) struct.unpack('i',数据长度) 二.上传下载文件作业 server imp ...
- python实现socket上传下载文件-进度条显示
在python的socket编程中,可以实现上传下载文件,并且在下载的时候,显示进度条,具体的流程如下图所示: 1. 服务器端代码如下: [root@python 519]# cat server.p ...
- Ajax+Python flask实现上传文件功能
HTML: <div > <input type="file" name="FileUpload" id="FileUpload&q ...
- python服务器文件上传下载+GUI【tkinter】
大概就是一个通过应用程序来和服务器打交道的这么一个,小东西 1.GUI 用的是tkinter # -*- coding: UTF-8 -*- from tkinter import * import ...
- FLASK实现上传下载功能
#!-*-coding=utf-8-*- # from flask import Flask # # app = Flask(__name__) # # # @app.route('/') # def ...
- python用ftplib上传下载中文报错解决
python中的中文编码一直以来都是一个极为头大的问题,经常抛出编码转换的异常,python中的str和unicode到底是一个什么东西呢?在python中提到unicode,一般指的是unicode ...
- Python socket文件上传下载
python网络编程 程序的目录结构 socketDemo ├── client │ ├── cli.py │ └── local_dir │ └── lianxijiangjie.mp4 ...
- python 实现远端ftp文件上传下载
python 实现ftp上传下载 * 脚本需要传入两个参数,参数1为需要从远端ftp站点下载文件名称,参数2为已知需要下载的文件md5值,文件下载完成后会自动进行md5值校验 * 运行示例 [root ...
- python paramiko实现ssh上传下载执行命令
paramiko ssh上传下载执行命令 序言 最近项目经常需要动态在跳板机上登录服务器进行部署环境,且服务器比较多,每次完成所有服务器到环境部署执行耗费大量时间.为了解决这个问题,根据所学的执行实现 ...
随机推荐
- fastjson =< 1.2.47 反序列化漏洞浅析
fastjson =< 1.2.47 反序列化漏洞浅析 iiusky 洛米唯熊 今天 文章出处: https://www.03sec.com/3240.shtmlhttps://www.secq ...
- 动态生成html文件
#include"stdio.h" main() { FILE *a; int x1,x2,N1=99,N2=60; char FileName[100]; for(x1=10;x ...
- 库&插件&框架&工具
nodejs 入门 nodejs 入门教程,大家可以在 github 上提交错误 2016 年最好用的表单验证库 SMValidator.js 前端表单验证工具分享 浅谈前端线上部署与运维 说到前端部 ...
- centos6.5和centos7如何搭建php环境(包括php7)
查看下centos的版本信息: #适用于所有的linux lsb_release -a #或者 cat /etc/redhat-release #又或者 rpm -q centos-release 安 ...
- vuex 讲解
vuex 状态的管理状态,它采用集中式存储管理应用的所有组件的状态,尤其是在中大型项目,则是很好的开发利器 vuex 的流程图 vuex 的优势: 1. vuex 的存储状态,响应式的 2. 他是所有 ...
- cad二次开发中DBText对象的外框GeometricExtents有问题?
CAD2007版本 acDoc.Editor.WriteMessage( string.Format("[{0:F1},{1:F1},{2:F1}] - [{3:F1},{4:F1},{5: ...
- LC 962. Maximum Width Ramp
Given an array A of integers, a ramp is a tuple (i, j) for which i < j and A[i] <= A[j]. The ...
- Oracle11g安装出现时未能满足某些最低安装要求
需要开启C盘共享,才能检测硬件是否满足要求.cmd命令:net share c$=c::或者勾选全部忽略,继续下一步安装. 可参考https://blog.csdn.net/huazicomeon/a ...
- 外国前端收费模板wrapbootstrap
https://wrapbootstrap.com/ 新闻模板 http://wrapbootstrap.com/preview/WB037B6R2
- ubuntu搭建ssh服务
本人在ubuntu16.4.4.0-13下测试 #man uname//用于打印系统信息 sudo apt install update sudo apt install openssh-server ...