python实现文件下载上传

一、文件下载到本地

py 复制代码
import requests
if __name__ == '__main__':
     response = requests.get("https://dfcv-shop.oss-cn-hangzhou.aliyuncs.com/dfcv-shop0177bf6b34ee46c68be412d04654439c.jpg")
     local_filename = "./dfcv-shop0177bf6b34ee46c68be412d04654439c.jpg"
     if response.status_code == 200:
         # 将文件内容写入本地文件
         with open(local_filename, 'wb') as file:
             file.write(response.content)
         print(f"文件 '{local_filename}' 下载成功!")
     else:
         print("下载失败")

二、服务端对外提供下载资源

py 复制代码
from flask import Flask, send_file

app = Flask(__name__)

@app.route('/download')
def download_file():
    file_path = 'E:\code\ZhkCode\Dockerfile'  # 替换为你要下载的文件路径
    return send_file(file_path, as_attachment=True)

if __name__ == '__main__':
    app.run(debug=True)

三、上传资源

html 复制代码
<!DOCTYPE html>
<html>
<head>
    <title>文件上传示例</title>
</head>
<body>
    <h2>上传文件</h2>
    <form method="POST" action="/upload" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="上传">
    </form>
</body>
</html>
py 复制代码
from flask import Flask, render_template, request

app = Flask(__name__)

# 允许上传的文件类型
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('/')
def upload_form():
    return render_template('index.html')

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return 'No file part'

    file = request.files['file']

    if file.filename == '':
        return 'No selected file'

    if file and allowed_file(file.filename):
        # 保存上传的文件到指定路径
        file.save('F:/uploads/' + file.filename)
        return 'File uploaded successfully'
    else:
        return 'Invalid file extension'

if __name__ == '__main__':
    app.run(debug=True)
相关推荐
油丶酸萝卜别吃3 分钟前
Mapbox GL JS 表达式 (expression) 条件样式设置 完全指南
开发语言·javascript·ecmascript
飞Link3 分钟前
【Django】Django的静态文件相关配置与操作
后端·python·django
爱吃大芒果24 分钟前
Flutter for OpenHarmony前置知识:Dart 语法核心知识点总结(下)
开发语言·flutter·dart
Ulyanov33 分钟前
从桌面到云端:构建Web三维战场指挥系统
开发语言·前端·python·tkinter·pyvista·gui开发
星火开发设计42 分钟前
C++ 函数定义与调用:程序模块化的第一步
java·开发语言·c++·学习·函数·知识
cypking1 小时前
二、前端Java后端对比指南
java·开发语言·前端
钟离墨笺1 小时前
Go语言--2go基础-->map
开发语言·后端·golang
lsx2024061 小时前
DOM CDATA
开发语言
Tony Bai1 小时前
Go 语言的“魔法”时刻:如何用 -toolexec 实现零侵入式自动插桩?
开发语言·后端·golang
CCPC不拿奖不改名2 小时前
两种完整的 Git 分支协作流程
大数据·人工智能·git·python·elasticsearch·搜索引擎·自然语言处理