日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

python-上传下载文件

發(fā)布時(shí)間:2023/12/9 python 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python-上传下载文件 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

https://www.cnblogs.com/jessicaxu/p/7891372.html

?

python-上傳下載文件

一、服務(wù)端接口

import flask, os,sys,time from flask import request, send_from_directoryinterface_path = os.path.dirname(__file__) sys.path.insert(0, interface_path) #將當(dāng)前文件的父目錄加入臨時(shí)系統(tǒng)變量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) #返回要下載的文件內(nèi)容給客戶端else:return '{"msg":"參數(shù)不正確"}'else:return '{"msg":"請(qǐng)輸入?yún)?shù)"}'# get方法:查詢當(dāng)前路徑下的所有文件 @server.route('/getfiles', methods=['get']) def getfiles():fpath = request.values.get('fpath', '') #獲取用戶輸入的目錄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') #獲取上傳的文件if fname:t = time.strftime('%Y%m%d%H%M%S')new_fname = r'upload/' + t + fname.filenamefname.save(new_fname) #保存文件到指定路徑return '{"code": "ok"}'else:return '{"msg": "請(qǐng)上傳文件!"}'server.run(port=8000, debug=True)

?

?二、客戶端發(fā)送請(qǐng)求

import requests import os#上傳文件到服務(wù)器 file = {'file': open('hello.txt','rb')} r = requests.post('http://127.0.0.1:8000/upload', files=file) print(r.text)#查詢fpath下的所有文件 r1 = requests.get('http://127.0.0.1:8000/getfiles',data={'fpath': r'download/'}) print(r1.text)#下載服務(wù)器download目錄下的指定文件 r2 = requests.get('http://127.0.0.1:8000/download',data={'filename':'hello_upload.txt', 'path': r'upload/'}) file = r2.text #獲取文件內(nèi)容 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)

?

?

總結(jié)

以上是生活随笔為你收集整理的python-上传下载文件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。