自学内容网 自学内容网

Flask 实现文件下载

Flask 实现文件下载

要通过URL下载 /home/data 目录下的图片,可以使用Python搭建一个简单的HTTP服务器,使用 Flask 框架来实现。

from flask import Flask, send_from_directory, abort
import os

app = Flask(__name__)

# 图片存放的目录
# IMAGE_DIRECTORY = './'
IMAGE_DIRECTORY = '/home/data'

@app.route('/images/<path:filename>', methods=['GET'])
def download_image(filename):
    try:
        # 检查文件是否存在,并返回文件
        return send_from_directory(IMAGE_DIRECTORY, filename)
    except FileNotFoundError:
        abort(404)  # 如果文件未找到,返回404错误

if __name__ == '__main__':
    # 启动Flask应用,默认监听在0.0.0.0:5000
    # app.run(debug=True)
    app.run(host='0.0.0.0', port=1213)
import requests
def download_image(url, save_path):
    try:
        # 发送GET请求
        response = requests.get(url)
        # 检查请求是否成功
        if response.status_code == 200:
            # 将内容写入文件
            with open(save_path, 'wb') as file:
                file.write(response.content)
            print(f'Image downloaded successfully: {save_path}')
        else:
            print(f'Failed to download image. Status code: {response.status_code}')
    except Exception as e:
        print(f'An error occurred: {e}')

if __name__ == '__main__':
    # 替换为您的服务器IP和图片文件名
    # url = "http://xxxx:1213/images/img1.jpeg"
    server_ip = 'xxxx'
    image_filename = 'img1.jpg'
    url = f'http://{server_ip}:1213/images/{image_filename}'
    
    # 设置保存路径
    save_path = f'./down_{image_filename}'

    # 下载图片
    download_image(url, save_path)

import requests

def download_image(url, filepath):
    response = requests.get(url)
    if response.status_code == 200:
        with open(filepath, 'wb') as f:
            f.write(response.content)

download_image("http://xxxx:1213/images/img1.jpeg", "./down_img1.jpg")

参考:
https://blog.csdn.net/yuanjc002/article/details/133633570


原文地址:https://blog.csdn.net/weixin_43815222/article/details/142524477

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!