Python 实现文件上传下载

admin 2024年2月21日07:35:07评论22 views字数 2576阅读8分35秒阅读模式

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

python -m http.server 9999

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

import requests
def 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 os
app = Flask(__name__)
# 配置文件上传路径UPLOAD_FOLDER = r'C:UsersAdministratoruploads'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 页面:

Python 实现文件上传下载

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

import requestsimport sys
url = '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>

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

Python 实现文件上传下载

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

全文完。

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

原文始发于微信公众号(生有可恋):Python 实现文件上传下载

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2024年2月21日07:35:07
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   Python 实现文件上传下载http://cn-sec.com/archives/2510782.html

发表评论

匿名网友 填写信息