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)
相关推荐
White_Can几秒前
《C++11:列表初始化》
c语言·开发语言·c++·vscode·stl
White_Can9 分钟前
《C++11:右值引用与移动语义》
开发语言·c++·stl·c++11
2501_9418705610 分钟前
从配置频繁变动到动态配置体系落地的互联网系统工程实践随笔与多语言语法思考
java·前端·python
比奇堡派星星11 分钟前
Linux4.4使用AW9523
linux·开发语言·arm开发·驱动开发
民乐团扒谱机14 分钟前
【微实验】数模美赛备赛MATLAB实战:一文速通各种“马尔可夫”(Markov Model)
开发语言·人工智能·笔记·matlab·数据挖掘·马尔科夫链·线性系统
Z1Jxxx14 分钟前
字符串翻转
开发语言·c++·算法
西西弗Sisyphus18 分钟前
Python FastAPI 和 Uvicorn 同步 (Synchronous) vs 异步 (Asynchronous)
python·fastapi·uvicorn
MistaCloud20 分钟前
Pytorch深入浅出(十三)之模型微调
人工智能·pytorch·python·深度学习
菜的不敢吱声21 分钟前
swift学习第2,3天
python·学习·swift
爱喝水的鱼丶23 分钟前
SAP-ABAP:全面破解SAP与第三方系统集成超时难题:从应急排查到根治方案
开发语言·sap·abap·接口集成·开发交流