如何通过Python将API返回的JPG图片文件保存至本地系统?
Python 保存API返回的JPG文件到本地
首先,从你提供的API响应中,我们可以提取出文件下载链接(links数组中rel="self"对应的href)和目标文件名(fileName字段),然后通过Python的requests库完成文件下载与本地保存。
实现步骤
- 解析API返回的JSON数据,提取关键信息
- 发送GET请求获取文件二进制内容
- 将二进制内容写入本地文件
完整代码示例
import requests import json # 你的API响应内容(已修正转义引号) api_response = '''{"contentType":"image/jpeg","createdTime":"2021-10-10T11:00:47.000Z","fileName":"Passport_Chris J Passport Color - pp.jpg","id":10144,"size":105499,"updatedTime":"2021-10-10T11:00:47.000Z","links":[{"rel":"self","href":"https://dafzprod.custhelp.com/services/rest/connect/v1.4/CompanyRegd.ManagerDetails/43/FileAttachments/10144?download="},{"rel":"canonical","href":"https://dafzprod.custhelp.com/services/rest/connect/v1.4/CompanyRegd.ManagerDetails/43/FileAttachments/10144"},{"rel":"describedby","href":"https://dafzprod.custhelp.com/services/rest/connect/v1.4/metadata-catalog/CompanyRegd.ManagerDetails/FileAttachments","mediaType":"application/schema+json"}]}''' # 解析JSON数据 response_data = json.loads(api_response) # 提取下载链接和目标文件名 download_url = next(link['href'] for link in response_data['links'] if link['rel'] == 'self') target_filename = response_data['fileName'] # 下载并保存文件(若API需认证,添加headers参数,如headers={'Authorization': 'Bearer YOUR_TOKEN'}) try: with requests.get(download_url, stream=True) as r: r.raise_for_status() # 检查请求是否成功 with open(target_filename, 'wb') as f: # 分块写入,避免内存占用过高 for chunk in r.iter_content(chunk_size=8192): f.write(chunk) print(f"文件已成功保存为: {target_filename}") except requests.exceptions.RequestException as e: print(f"下载失败: {e}")
注意事项
- 如果API需要身份验证(如Bearer令牌、API密钥),请在
requests.get方法中添加对应的headers参数 stream=True用于分块处理文件,适合大文件下载,也能适配你这个100KB左右的文件- 代码中用
next()快速定位到rel="self"的下载链接,确保能正确获取文件资源地址
内容的提问来源于stack exchange,提问作者muhamed fasil
相关产品推荐
相关产品推荐

