请求 - 从URL上传文件
我正在尝试通过API调用将文件上传到网站。
当文件放在我的计算机上时,
import requests
url = "https://api.app.com/api/1/profile/1234/verification/44"
files = {"file": open("licence.jpg", "rb")}
headers = {
"Accept": "application/json",
"Authorization": "Bearer blah:blah"
}
response = requests.post(url, files=files, headers=headers)
print(response.text)
我可以从一个网站上上传文档,该文档包含一个安全的链接,而不是在我的计算机上上传该文档。假设所产生的链接就是这样。
secure_link = "https://secure-data.company.com?k=i1jdXN0b21lci1rZXktbWQ1PU5DNCUyRjNTand4TllrUGpNSFc3SmVtUSUzRCUzRCZYLUFtei1"
我已经尝试了以下代码,但似乎无法使其正常工作。
r = requests.get(get_url, stream=True)
if r.status_code == 200:
r.raw.decode_content = True # decompress as you read
files = {'file': ('test.jpg', r.raw)
}
requests.post(post_url,headers=headers, files=files)
response = requests.post(post_url, files=files, headers=headers)
print(response.text)
I'm trying to upload a file to a website via an API call.
I'm able to get this working when the file is on my computer with:
import requests
url = "https://api.app.com/api/1/profile/1234/verification/44"
files = {"file": open("licence.jpg", "rb")}
headers = {
"Accept": "application/json",
"Authorization": "Bearer blah:blah"
}
response = requests.post(url, files=files, headers=headers)
print(response.text)
I now need to upload a document from a website that contains a secure link to the file instead of it being on my computer. Let's say the link produced is this.
secure_link = "https://secure-data.company.com?k=i1jdXN0b21lci1rZXktbWQ1PU5DNCUyRjNTand4TllrUGpNSFc3SmVtUSUzRCUzRCZYLUFtei1"
I've tried the following code below but can't seem to get it to work.
r = requests.get(get_url, stream=True)
if r.status_code == 200:
r.raw.decode_content = True # decompress as you read
files = {'file': ('test.jpg', r.raw)
}
requests.post(post_url,headers=headers, files=files)
response = requests.post(post_url, files=files, headers=headers)
print(response.text)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您希望它的行为与本地代码相同,则只需将文件下载到临时位置,然后在文件字典打开呼叫中递给其温度路径。
否则,您只需加载对变量的响应
If you are wanting it to behave the same way as your local code you can just download the file to a temporary location then hand its temp path in your files dictionary open call.
Otherwise you can just load the response to a variable then do the work the files= argument does manually