我正在尝试使用仅显示以下内容的API上传文件:
要求 请求正文应包含文件的内容。 https://developer.fortnox.se/documentation/resources/inbox/
到目前为止,我已经尝试过:
headers = {
"Access-Token": settings.FORTNOX_ACCESS_TOKEN,
"Client-Secret": settings.FORTNOX_CLIENT_SECRET,
"Content-Type": "multipart/form-data",
"Accept": "application/json",
}
file = open(invoice.file.path, 'rb').read()
r = requests.post("https://api.fortnox.se/3/inbox", data=file, headers=headers)
这给了我一个错误:
Ingen fil var uppladdad。 (没有文件上传)
headers = {
"Access-Token": settings.FORTNOX_ACCESS_TOKEN,
"Client-Secret": settings.FORTNOX_CLIENT_SECRET,
"Content-Type": "multipart/form-data",
"Accept": "application/json",
}
h = httplib2.Http()
file = open(invoice.file.path, 'rb').read()
resp, content = h.request('https://api.fortnox.se/3/inbox', "POST", body=file, headers=headers)
这给了我同样的错误:
Ingen fil var uppladdad。 (没有文件上传)
是否还有其他方法可以将文件添加到请求正文中,或者我在这里做错了什么?
感谢您的帮助。
答案 0 :(得分:0)
就我而言,我能够从put请求中上传文件,如下所示:
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
def upload_localfile(filepath,server_data):
multipart_data = MultipartEncoder(
fields={
'file': (filepath, open(filepath, 'rb'), 'text/plain')
}
)
response=requests.put(
server_data,
data=multipart_data,
headers={'Content-Type': multipart_data.content_type}
)
答案 1 :(得分:0)
基于mee的回答,我终于使它起作用了。这可以达到目的:
multipart_data = MultipartEncoder(
fields={
'file': (invoice.file.path, open(invoice.file.path, 'rb'), 'text/plain')
}
)
headers = {
"Access-Token": settings.FORTNOX_ACCESS_TOKEN,
"Client-Secret": settings.FORTNOX_CLIENT_SECRET,
"Content-Type": multipart_data.content_type,
"Accept": "application/json",
}
r = requests.post("https://api.fortnox.se/3/inbox", headers=headers, data=multipart_data)