【问题标题】:How to upload the file in POST requests (form-data)?如何在 POST 请求(表单数据)中上传文件?
【发布时间】:2021-03-15 07:57:34
【问题描述】:

我使用这个 GET request https://api.telegram.org/file/bot<token>/<file_path> 允许我们从 Telegram API 下载文件。 现在我需要在第二个 POST 请求(表单数据)中发送这个文件。

现在我的代码出现这样的错误

Exception: embedded null byte Traceback

代码sn-p

# Download the file via GET request of the Telegram API.
response = requests.get("{0}/file/bot{1}/{2}".format(TELEGRAM_API_URL, telegram_bot_token, file_path))

files = [
    ('file', (file_name, open(response.content, 'rb'), 'application/octet-stream')) # error
]

# Upload the file via POST request.
response = requests.post(FILE_STORAGE_SERVICE_API_URL, files=files)

问题

如何正确转换文件以便 POST 请求可以处理它?

【问题讨论】:

  • response.content 是没有编码的字节。此外,我认为您应该提供可运行的代码。我无法运行您的代码,因为您的代码中没有网址。
  • @XuQiushi 谢谢你的回答。我试图删除.encode() 方法,但问题仍然相同。在这里,我只想展示没有我的凭据的概念。请谅解。
  • 即使您想保留您的凭据,您也应该提供响应等数据。没有更多信息,我只能猜测您的问题。我认为 response.content 中有 '\0' 。当您在路径中打开带有 '\0' 的文件时,您将收到此错误。你可以试试'open('\0.txt')',它会产生同样的错误。
  • response.content的数据类型为<class 'bytes'>。其实response.content的值非常大。您可以从这个临时的link 下载数据。你可以检查一下。它以以下值开头:b'\x00\x00\x00 ftypisom\x00\x00\x02\x00isomiso2avc1mp41\x00\x00\x03Fmoov....
  • 您已经拥有文件字节。您可以尝试类似 'requests.post(FILE_STORAGE_SERVICE_API_URL, files={'file': response.content})'

标签: python post python-requests multipartform-data


【解决方案1】:

我从第一个请求中获取的response.content 的数据类型是<class 'bytes'>

工作代码sn-p:

response = requests.get("{0}/file/bot{1}/{2}".format(TELEGRAM_API_URL, telegram_bot_token, file_path))

files =  {
    "file": response.content
}

requests.post(FILE_STORAGE_SERVICE_API_URL, files=files)

【讨论】:

    猜你喜欢
    • 2016-06-29
    • 1970-01-01
    • 2021-08-10
    • 2015-05-20
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多