def get_file_info(file_url):
    """
    根据提供的URL获取文件的相关信息。
    参数:file_url (str): 文件的网络地址。
    返回:dict: 包含文件名、后缀名、内容类型和文件大小等信息的字典;如果失败则返回None。
    """
    data = dict()
    if not file_url:
        return return_dict(400, "file_url参数不能为空")
    try:
        # 发送HEAD请求以获取文件信息,而不下载整个文件。allow_redirects=True确保跟随重定向。
        response = requests.head(file_url, allow_redirects=True)
        response.raise_for_status()  # 检查响应状态码是否为200以外的值,抛出异常表示有错误
        # 初始化文件信息字典,尝试从响应头中获取内容类型和文件大小
        data['file_type']  = response.headers.get('content-type')                  # 获取MIME类型
        data['file_size'] = int(response.headers.get('content-length', 0)) or None   # 获取文件大小(字节)
        # 尝试从Content-Disposition头部或URL路径中提取文件名和扩展名
        content_disposition = response.headers.get('content-disposition')
        if content_disposition:
            # 如果存在Content-Disposition头部,使用正则表达式查找文件名
            import re
            match = re.search(r'filename="([^"]+)"', content_disposition)
            filename = match.group(1) if match else None  # 如果匹配成功,则取文件名
        else:
            # 如果没有Content-Disposition头部,从URL路径中提取文件名
            parsed_url = urlparse(file_url)
            path = unquote(parsed_url.path)  # 解码URL中的百分号编码字符
            filename = os.path.basename(path) if path else None  # 获取URL路径的最后一部分作为文件名
        # 如果成功获取到文件名,则分离文件名和扩展名,并加入到returnjson字典中
        if filename:
            data['file_name'], data['file_ext'] = os.path.splitext(filename)
        # 如果确实获取到了一些有效的文件信息,则返回returnjson字典;否则返回None
        if any(data.values()):
            return return_dict(200, "获取文件信息成功", data)
        else:
            return return_dict(400, "获取文件信息失败")
    except requests.RequestException as e:
        # 捕获所有由requests库抛出的异常,并打印错误消息
        return return_dict(400, f"报错信息:{e}")根据提供的URL获取文件的相关信息
相关推荐
- 
                            生成图片from PIL import Image, ImageColor, ImageDraw, ImageFont, ImageFilterdef create_image_with_text(size, color, text, font_path, font_size, text_color, shadow_color, output_path): """ Create a new image of specified size and color with centered text that has a border and shadow. :param size: A tuple con 查看详情
- 
                            获取指定目录下的所有图片信息1 获取指定目录下的所有图片信息// 获取指定目录下的所有图片信息 public function getImagesInfo($directory) { $images = []; // 创建递归目录迭代器 $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY ); // 遍历目录中的每个文件 foreach ( 查看详情
- 
                            Thinkphp各版本的PHP要求ThinkPHP 8.0:运行环境要求PHP8.0+,兼容PHP8.3ThinkPHP 6.1:运行环境要求PHP7.2+,兼容PHP8.1ThinkPHP 6.0:运行环境要求PHP7.2+,兼容PHP8.1ThinkPHP 5.1:运行环境要求PHP5.6+,兼容PHP8.0ThinkPHP 5.0:运行环境要求PHP5.4+,兼容PHP7.3 查看详情
 智享笔记
								    智享笔记								 
                             
                             
                             
                            