python文件上传下载
#服务端
#!usr/bin/python
# -*- coding: utf-8 -*
import flask, os,sys,time,datetime,urllib
from flask import request, send_from_directory
from lxml import etree
interface_path = os.path.dirname(__file__)
sys.path.insert(0, interface_path) #将当前文件的父目录加入临时系统变量
server = flask.Flask(__name__)
#get方法:指定目录下载文件
@server.route('/download', methods=['get'])
def download():
fpath = request.values.get('path', '') #获取文件路径
fname = request.values.get('filename', '') #获取文件名
if fname.strip() and fpath.strip():
print(fname, fpath)
if os.path.isfile(os.path.join(fpath,fname)) and os.path.isdir(fpath):
return send_from_directory(fpath, fname, as_attachment=True) #返回要下载的文件内容给客户端
else:
return '{"msg":"参数不正确"}'
else:
return '{"msg":"请输入参数"}'
# get方法:查询当前路径下的所有文件
@server.route('/getfiles', methods=['get'])
def getfiles():
fpath = request.values.get('fpath', '') #获取用户输入的目录
mima = request.values.get('mima','') #获取上传的文件
if mima != 'zheshiyigeshenqidemima':
return '密码错误!'
print(mima)
print(fpath)
if os.path.isdir(fpath):
filelist = os.listdir(fpath)
files = [file for file in filelist if os.path.isfile(os.path.join(fpath, file))]
return '{"files":"%s"}' % files
# post方法:上传文件的
@server.route('/upload', methods=['post'])
def upload():
fname = request.files.get('file') #获取上传的文件
mima = request.values.get('mima','') #获取上传的文件
if mima != 'zheshiyigeshenqidemima':
return '密码错误!'
if fname:
t = time.strftime('%Y%m%d%H%M%S')
new_fname = r'v191/' + fname.filename
# return new_fname
fname.save(new_fname) #保存文件到指定路径
os.system("D:/hotupdate/v191/Newcopy.bat")
nowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')#现在
return '['+nowTime+']:'+'完成热更新!'
else:
return '{"msg": "请上传文件!"}'
@server.route('/ceshi', methods=['get'])
def ceshi():
name = request.values.get('name','')
# for a in range(10):
#url = 'https://book.douban.com/top250?start={}'.format(a*25)
url = 'https://www.bilibili.com/ranking?spm_id_from=333.11.banner_link.2'
page = urllib.urlopen(url)
htmlcode = page.read()
html = etree.HTML(htmlcode)
result = html.xpath('//*[@id="app"]/div[2]/div/div[1]/div[2]/div[3]/ul/li/div[2]/div[2]/div[1]/a/span/text()')
return result[85].encode('GBK','ignore')
server.run(host='0.0.0.0',port=9006, debug=True)
下面是客户端
from __future__ import division
import math
import sys
import requests
import os
def progressbar(cur,total):
percent = '{:.2%}'.format(cur / total)
sys.stdout.write('\r')
sys.stdout.write('[%-50s] %s' % ( '=' * int(math.floor(cur * 50 /total)),percent))
sys.stdout.flush()
if cur == total:
sys.stdout.write('\n')
def setwenjian():
#上传文件到服务器
file = {'file': open('build/v191.rar','rb')}
r = requests.post('http://39.106.210.142:9006/upload', files=file,data={'mima':'zheshiyigeshenqidemima'})
print(r.text)
#查询fpath下的所有文件
r1 = requests.get('http://39.106.210.142:9006/getfiles',data={'fpath': r'v191/','mima':'zheshiyigeshenqidemima'})
print(r1.text)
# #下载服务器download目录下的指定文件
# r2 = requests.get('http://39.106.210.142:9006/download',data={'filename':'hello_upload.txt', 'path': r'upload/'})
# file = r2.text #获取文件内容
# basepath = os.path.join(os.path.dirname(__file__), r'download/')
# with open(os.path.join(basepath, 'hello_download.txt'),'w',encoding='utf-8') as f: #保存文件
# f.write(file)
def my_callback():
# Your callback function
# print monitor.bytes_read
e = MultipartEncoder(fields= {'file': open('build/v191.txt','rb')})
m = MultipartEncoderMonitor(e, my_callback)
r = requests.post('http://39.106.210.142:9006/upload', data=m,headers={'Content-Type': m.content_type})
if __name__ == '__main__':
setwenjian()
# file_size = 102400000
# size = 1024
# while file_size > 0:
# progressbar(size*10/file_size,10)
# file_size -= 1024