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)
相关推荐
nimadan121 小时前
**AI漫剧软件2025推荐,解锁高性价比创意制作新体验**
人工智能·python
姜太公钓鲸2333 小时前
ROM就是程序存储器,实际的存储介质是Flash闪存。上述描述中的程序存储器是什么意思?
开发语言·javascript·ecmascript
Java后端的Ai之路3 小时前
【JDK】-JDK 21 新特性内容
java·开发语言·后端·jdk·jdk21
wjs20243 小时前
JavaScript 作用域
开发语言
yunhuibin3 小时前
GoogLeNet学习
人工智能·python·深度学习·神经网络·学习
m0_531237174 小时前
C语言-指针终阶
c语言·开发语言
散峰而望4 小时前
C++ 启程:从历史到实战,揭开命名空间的神秘面纱
c语言·开发语言·数据结构·c++·算法·github·visual studio
易辰君4 小时前
【Python爬虫实战】正则:中文匹配与贪婪非贪婪模式详解
开发语言·爬虫·python
普通网友4 小时前
PHP语言的正则表达式
开发语言·后端·golang
黎雁·泠崖4 小时前
Java常用类核心详解(七):正则表达式 Regex 从入门到实战
java·开发语言·正则表达式