How To Use Python To Send A Multipart Pdf Request To Onenote
Solution 1:
The answer it turns out is that Python encodes blank lines as "\n" but OneNote requires "\r\n". It also requires a blank line ("\r\n") after the final boundary. Finally, it can't have any leading whitespace in the body (no indents) for the Content-Type and Content-Disposition lines. (There should also be a blank line after each Content-Disposition line.)
For example, if this was the body:
"""--MyBoundary
Content-Type: text/html
Content-Disposition: form-data; name="Presentation"
Some random text
--MyBoundary
Content-Type: text/text
Content-Disposition: form-data; name="more"; filename="more.txt"
More text
--MyBoundary--
"""
it should be represented by the string
'--MyBoundary\r\nContent-Type: text/html\r\nContent-Disposition: form-data; name="Presentation"\r\n\r\nSome random text\r\n--MyBoundary\r\nContent-Type: text/text\r\nContent-Disposition: form-data; name="more"; filename="more.txt"\r\n\r\nMore text\r\n--MyBoundary--\r\n'
which can be made just by typing the text inside three """ quotes (which will automatically create \n in the final string wherever there's a blank line) and then replacing the "\n" with "\r\n":
body = body.replace("\n", "\r\n")
The headers would be:
headers = {"Content-Type":"multipart/form-data; boundary=MyBoundary",
"Authorization" : "bearer " + access_token}
Finally, you would POST the call like this:
session = requests.Session()
request = requests.Request(method="POST", headers=headers,
url=url, data=body)
prepped = request.prepare()
response = session.send(prepped)
Solution 2:
You need to construct the full HTTP request, not just send along the HTML.
For your body, try constructing the full body as you posted in your question.
--MyAppPartBoundary
Content-Disposition:form-data; name="Presentation"
Content-type:text/html
<!DOCTYPE html><html>
// truncated
</html>
--MyAppPartBoundary
Content-Disposition:form-data; name="OfficeLeasePartName"
Content-type:application/pdf
... PDF binary data ...
--MyAppPartBoundary--
Make sure you set the content-type header correctly:
Content-Type:multipart/form-data; boundary=MyAppPartBoundary
Post a Comment for "How To Use Python To Send A Multipart Pdf Request To Onenote"