乐于分享
好东西不私藏

Python 实现文件上传下载

Python 实现文件上传下载

Python 实现文件下载比较容易,使用自带的 http.server 模块即可搭建一个简单的文件下载服务:

python -m http.server 9999

在代码中也可以通过 requests 模块实现 client 端的下载:

import requestsdef download_file():    web_resource = 'http://localhost:9999/IP.pkl'    response = requests.get(web_resource)    if response.status_code == 200:        with open('IP.pkl', 'wb') as file:            file.write(response.content)        #print('文件下载成功!')    else:        pass        #print(f'文件下载失败,状态码: {response.status_code}')

使用 python 实现文件上传会稍微麻烦一点,不考虑 ftp、ssh 等文件上传方式,容易实现的就只剩 web post 方式上传了。

需要先实现一个 web 上传页面:

from flask import Flask, request, redirect, url_forfrom werkzeug.utils import secure_filenameimport osapp = Flask(__name__)# 配置文件上传路径UPLOAD_FOLDER = r'C:\Users\Administrator\uploads'app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER# 允许上传的文件类型ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}# 检查文件扩展名是否在允许的范围内def allowed_file(filename):    return '.' in filename and \           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS@app.route('/', methods=['GET', 'POST'])def upload_file():    if request.method == 'POST':        # 检查是否有文件被上传        if 'file' not in request.files:            return redirect(request.url)        file = request.files['file']        # 如果用户没有选择文件,浏览器提交的表单会不包含文件名        if file.filename == '':            return redirect(request.url)        if file and allowed_file(file.filename):            # 将文件名安全保存            #filename = secure_filename(file.filename)            filename = file.filename            # 将文件保存到指定路径            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))            return redirect(url_for('uploaded_file', filename=filename))    return '''    <!doctype html>    <title>文件上传</title>    <h1>上传一个文件</h1>    <form method=post enctype=multipart/form-data>      <input type=file name=file>      <input type=submit value=上传>    </form>    '''@app.route('/uploads/<filename>')def uploaded_file(filename):    return f'''    <h1>文件上传成功!</h1>    <p>文件名: {filename}</p>    <p><a href="{url_for('upload_file')}">返回</a></p>    '''if __name__ == '__main__':    app.run(debug=True)

使用前需要先安装 Flask 模块:

pip install Flask

运行代码后会启动 5000 端口:

(.venv) bash$ python ../upload.py * Serving Flask app 'upload' * Debug mode: onWARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on http://127.0.0.1:5000Press CTRL+C to quit * Restarting with stat * Debugger is active! * Debugger PIN: 104-829-486

访问 http://127.0.0.1:5000 会显示以下 web 页面:

通过鼠标点击测试可以正常上传文件,此时可以通过 requests 模块测试 post 上传功能:

import requestsimport sysurl = 'http://localhost:5000'  # 上传文件的目标 URLfile_path = sys.argv[1]  # 要上传的文件路径# 打开文件with open(file_path, 'rb') as file:    files = {'file': file}  # 构建文件参数,'file' 是服务器端接收文件的字段名    response = requests.post(url, files=files)  # 发送 POST 请求print(response.text)  # 打印服务器返回的响应内容

在命令行测试上传功能:

d:\> python client.py 双拼.txt     <h1>文件上传成功!</h1>    <p>文件名: 双拼.txt</p>    <p><a href="/">返回</a></p>

在文件目录中可以查看已经上传的文件:

通过搭建 web 上传服务,可以实现简单的文件上传。如果程序需要通过上传、下载更新配置文件,这里提供了一种思路。

全文完。

如果转发本文,文末务必注明:“转自微信公众号:生有可恋”。

本站文章均为手工撰写未经允许谢绝转载:夜雨聆风 » Python 实现文件上传下载

评论 抢沙发

8 + 1 =
  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
×
订阅图标按钮