目前有一张网络上的图片(url)有时效性(2个小时)
怎么把这张图片上传到宜搭云存储里呢?
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
要将网络上的时效性图片(URL有效期为2小时)上传到宜搭云存储,请按照以下步骤操作:
import requests
import time
# 配置参数
IMAGE_URL = "https://example.com/your-image.jpg" # 替换为你的图片URL
APP_KEY = "你的宜搭应用AppKey" # 宜搭开放平台获取
APP_SECRET = "你的宜搭应用AppSecret" # 宜搭开放平台获取
CORP_ID = "你的企业CorpId" # 钉钉企业ID
APP_TYPE = "com.dingtalk.xxxxx" # 宜搭应用标识符
# 1. 下载网络图片
def download_image(url):
response = requests.get(url)
if response.status_code == 200:
return response.content
raise Exception("图片下载失败")
# 2. 获取宜搭访问令牌
def get_access_token():
url = f"https://oapi.dingtalk.com/gettoken?appkey={APP_KEY}&appsecret={APP_SECRET}"
response = requests.get(url)
return response.json()["access_token"]
# 3. 上传到宜搭云存储
def upload_to_yida(file_data, file_name):
access_token = get_access_token()
url = "https://api.dingtalk.com/v1.0/yida/files/upload"
headers = {
"x-acs-dingtalk-access-token": access_token
}
params = {
"corpId": CORP_ID,
"appType": APP_TYPE,
"fileName": file_name
}
files = {'file': (file_name, file_data)}
response = requests.post(url, headers=headers, params=params, files=files)
return response.json()
# 执行上传
try:
# 生成唯一文件名(防止重复)
file_name = f"image_{int(time.time())}.jpg"
# 获取图片二进制数据
image_data = download_image(IMAGE_URL)
# 上传到宜搭
result = upload_to_yida(image_data, file_name)
print("上传成功!文件信息:")
print(f"文件ID: {result['fileId']}")
print(f"下载链接: {result['downloadUrl']}")
except Exception as e:
print(f"上传失败: {str(e)}")
时效性处理:
宜搭参数获取:
APP_KEY
/APP_SECRET
:宜搭开放平台 > 应用开发 > 应用凭证CORP_ID
:钉钉企业管理后台 > 企业信息APP_TYPE
:宜搭应用编辑页URL中的参数(如:https://yida.dingtalk.com/app/APP_TYPE/home
)返回结果:
fileId
和downloadUrl
fileId
引用该文件宜搭官方文档参考:文件上传接口