【问题标题】:upload string as image to trello api将字符串作为图像上传到 trello api
【发布时间】:2021-12-19 15:17:55
【问题描述】:

我正在尝试将图像文件上传到 trello api。 下面的代码完成了这项工作,但文件是以文本字符串的形式上传的。

C:/file 包含一个文本字符串。 如果我使用该字符串并在https://codebeautify.org/base64-to-image-converter 之类的在线base64 转换器中运行它,我会得到一张精美的png 图像。

API 文档指定我可以将文件名、mimetype 设置为字符串,并将文件附加为 multipart/form-data 格式:二进制

https://developer.atlassian.com/cloud/trello/rest/api-group-cards/#api-cards-id-attachments-post

如何在上传之前将此图片转换为图片?

import requests
import base64

key = "xxx"
token = "yyy"

url = "https://api.trello.com/1/cards/618390bbdc3cb10550c9912b/attachments"

pathToFile ="C:/file"

f = open(pathToFile, "r")
file = f.read()
f.close()

message_bytes = file.encode('ascii')
base64_bytes = base64.b64encode(message_bytes)
base64_message = base64_bytes.decode('ascii')

response = requests.post(url, params={'token':token,'key':key, 'mimeType ':'png', 'name':'fisk.png'}, files={'file':base64_message})

【问题讨论】:

    标签: python python-3.x api python-requests base64


    【解决方案1】:

    使用 Adrian Sutton https://community.atlassian.com/t5/Trello-questions/Mime-types-of-attachments-uploaded-to-Trello/qaq-p/1369920 的这篇帖子

    我最终得到了这段代码,它也处理了 mimetype corect:

    import requests
    import base64
    
    def attachFileToCardID(key,token, trelloCardID, theFile, theName, theMIMEtype):
        imgdata = base64.b64decode(file)
        resp = requests.post("https://trello.com/1/cards/{}/attachments".format(trelloCardID),
                             params={'key': key, 'token': token},
                             files={'file': (theName, imgdata, theMIMEtype)})
        return resp.status_code
    
    key = "xxx"
    token = "yyy"
    
    pathToFile ="C:/file.txt"
    
    f = open(pathToFile, "r")
    file = f.read()
    f.close()
    
    x = attachFileToCardID(key,token,'zzz', file, 'filename.png','image/png')
    

    【讨论】:

      猜你喜欢
      • 2017-06-21
      • 2016-09-03
      • 2019-04-11
      • 2021-07-28
      • 2018-12-19
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多