• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
_夕颜
博客园    首页    新随笔    联系   管理    订阅  订阅
Falsk 大文件上传/下载(send_from_directory)

下载接口:

服务端flask下载接口

@app.route("/api/download/", methods=["POST"])
def download():
    try:
        logger.debug("download start")
        param = request.get_json(force=True).get('param')
        logger.debug("download({})".format(param))
        file_path = param.get('file_path')
        file_name = param.get('file_name')
        base_dir = u"C:\\Program Files\\download"
        file_dir = os.path.join(base_dir, file_path)
        file_abs_path = os.path.join(file_dir, file_name)
        logger.debug("send_from_directory file_dir ({}) ,file_name({})".format(file_dir, file_name))
        response_file = send_from_directory(file_dir, filename=file_name, as_attachment=False)
        response = make_response(response_file)
        response.headers["Content-Disposition"] = "attachment; filename={}".format(file_name.encode().decode("latin-1"))
        response.headers["Content-Length"] = os.stat(file_abs_path).st_size
        response.headers["Content-Type"] = "application/octet-stream"
        return response
    except:
        logger.debug("download failed ({})".format(traceback.format_exc()))
        response = {"status": 9999}
        return jsonify(response)

客户端下载接口

url = "https://{}:{}/api/download/".format(server_ip, get_https_port())
data = {"param": {
    "file_path": file_path,
    "file_name": file_name
}}
save_to = "/home"

try:
    logger.debug("download, url[%s] data:%s" % (url, data))
   download_headers = {"Content-Type": "application/json"} res
= requests.post(url=url, headers=download_headers, data=json.dumps(data), verify=False) logger.debug('download response status[%s] headers:%s' % (res.status_code, res.headers)) if not os.path.exists(save_to): os.makedirs(save_to) save_path = os.path.join(save_to, file_name) with open(save_path, "wb") as fp: for chunk in res.iter_content(1024): if not chunk: break fp.write(chunk)

上传接口:

服务接口上传文件接口

@app.route("/api/upload/", methods=["POST"])
def upload():
    if request.method == "POST":
        try:
            logger.debug("upload vars ({})".format(request.files))
            file = request.files['file']
            content = file.read()
            # bdecode(content)

            path = "/home"
            file_path = os.path.join(path, file_name)
            if os.path.exists(file_path):
                os.remove(file_path)

            with open(file_path, "wb") as f:
                f.write(content)
                f.flush()
                f.close()
            return jsonify({"status": 0, "data": []})
        except:
            logger.debug("save upload file fail ({})".format(traceback.format_exc()))
            return jsonify({"status": 1, "data": []})

客户端上传接口:

url = "https://{}:{}/api/download/".format("192.168.11.200", "8000")
file_path = "/home/dddd/aaa.txt"
file_name = os.path.split(file_path)[-1]
send_data = {}

headers = {
'Connection': 'keep-alive',
'User-Agent': 'P2pclient with Linuxos',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
}

if not send_data:
    with open(file_path, 'rb')as fp:
        file_list = {'file': (file_name, fp, ''), "uuid": timestamp_uuid, "sign": sign,
                     "Authorization": "token"}
        response = requests.post(url, headers=headers, timeout=15,
                                 files=file_list, verify=False)
else:
    with open(file_path, 'rb')as fp:
        file_list = {'file': (file_name, fp, ''), "uuid": timestamp_uuid, "sign": sign,
                     "Authorization": "token"}
        response = requests.post(url, headers=headers, timeout=15,
                                 data=send_data, files=file_list, verify=False)
logger.debug('upload {} to {} response {}'.format(file_path, url, response.__dict__))
data = response.json()
if data.get('status') == 0:
    logger.debug('upload {} to {} successed!'.format(file_path, url))
    return True
else:
    logger.debug('upload {} to {} failed, try again ... {}'.format(file_path, url, i))
    return False

 

posted on 2022-08-21 17:00  __夕颜  阅读(807)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3