使用Python调用免费API实现文件上传及跨设备获取的方案咨询
可实现Python跨设备文件上传/获取的免费API推荐
- 公有云对象存储免费额度版:国内主流云厂商的对象存储服务(阿里云OSS、腾讯云COS、七牛云Kodo)均提供长期免费额度,单文件最大支持5GB,每月有免费的存储容量和下行流量配额,官方提供Python SDK,调用简单,稳定性高。
- 匿名文件托管API:第三方免费文件托管服务支持无注册调用,单文件限制多在200MB以内,适合临时文件分享,缺点是部分服务有文件有效期限制。
- MongoDB Atlas 云服务:MongoDB官方提供的免费托管集群有512MB的永久存储额度,支持GridFS规范存储任意大小的文件,只要使用同一集群访问凭证,即可在任意联网设备上读写文件,不需要额外配置存储规则,适合小容量文件的跨设备同步。
MongoDB Atlas 使用前置准备
提前注册MongoDB Atlas账号,创建免费M0规格集群,获取集群连接字符串,开启对应IP访问权限、创建数据库读写用户即可使用。
需先安装依赖:pip install pymongo python-dotenv
跨设备文件上传示例代码
from pymongo import MongoClient from gridfs import GridFS import os # 替换为自己的MongoDB Atlas集群连接字符串 MONGO_URI = "你的MongoDB Atlas集群连接字符串" client = MongoClient(MONGO_URI) # 初始化存储用的数据库和GridFS实例 db = client["file_storage_db"] fs = GridFS(db, collection="personal_files") def upload_file(local_path: str, custom_filename: str = None): if not custom_filename: custom_filename = os.path.basename(local_path) with open(local_path, "rb") as f: file_id = fs.put(f, filename=custom_filename) print(f"文件上传成功,文件ID:{file_id},可凭该ID或文件名在任意设备下载") return file_id # 调用示例 if __name__ == "__main__": upload_file("./本地测试文件.docx", "工作文档备份.docx")
跨设备文件获取示例代码
from pymongo import MongoClient from gridfs import GridFS # 和上传端使用相同的连接字符串即可实现跨设备访问 MONGO_URI = "你的MongoDB Atlas集群连接字符串" client = MongoClient(MONGO_URI) db = client["file_storage_db"] fs = GridFS(db, collection="personal_files") def download_file(identifier, save_path: str, use_file_id: bool = True): # 支持用文件ID或文件名查询 if use_file_id: file_obj = fs.get(identifier) else: file_obj = fs.find_one({"filename": identifier}) if not file_obj: raise Exception("未查询到对应文件") with open(save_path, "wb") as f: f.write(file_obj.read()) print(f"文件下载完成,已保存到{save_path}") # 调用示例 if __name__ == "__main__": # 用上传时返回的文件ID下载 download_file("上传接口返回的文件ID字符串", "./本地保存路径.docx") # 也可以用文件名下载 # download_file("工作文档备份.docx", "./本地保存路径.docx", use_file_id=False)
注意:免费使用MongoDB Atlas时请合理设置IP白名单和数据库用户权限,避免数据泄露。如果存储的文件普遍小于16MB,可直接转成Base64格式存储在普通文档中,读写速度比GridFS更快。
内容的提问来源于stack exchange,提问作者TLS_R
相关产品推荐
相关产品推荐

