0

i'm trying to upload multiple files (2 in this example) with multipart using a python client.

this is my request

import requests
import base64
import json

access_token = "xxxxxx"
instance_url = "https://xxxxxx.com"    
path1 = "document1.pdf"
        with open(path1, "rb") as f1:
            doc1 = base64.b64encode(f1.read()).decode('utf-8')

path2 = "document2.pdf"
with open(path2, "rb") as f2:
    doc2 = base64.b64encode(f2.read()).decode('utf-8')

boundary = 'string_boundary'
body = '--' + boundary + '\r\n'
body+='Content-Disposition: form-data; name="collection"'+'\r\n'
body+='Content-Type: application/json\r\n\r\n'
bodyjson = '''{
    "allOrNone" : false,
    "records" :
    [
        {
            "attributes" :
            {
                "type" : "ContentVersion",
                "binaryPartName": "doc1",
                "binaryPartNameAlias": "VersionData"
            },
            "Title" : "BoardingCard",
            "PathOnClient" : "BoardingCard.pdf"
        },
        {
            "attributes" :
            {
                "type" : "ContentVersion",
                "binaryPartName": "doc2",
                "binaryPartNameAlias": "VersionData"
            },
            "Title" : "documentToSave",
            "PathOnClient" : "documentToSave.pdf"
        }
    ]
}'''
body+=bodyjson+'\r\n\r\n'
body+='--'+boundary
contentType = 'application/octet-stream'
body+='\r\nContent-Disposition: form-data; name="doc1"; filename="BoardingCard.pdf"'+'\r\n'
body+='Content-Type: application/octet-stream' + '\r\n\r\n'
body+= doc1
body+='\r\n\r\n--' + boundary + '\r\n'
body+='Content-Disposition: form-data; name="doc2"; filename="documentToSave.pdf"'+'\r\n'
body+='Content-Type: application/octet-stream' + '\r\n\r\n'
body+=doc2
body+='\r\n\r\n--' + boundary +'--'


headers = {
        'Content-type': 'multipart/form-data; boundary="'+boundary+'"',
        'Authorization': 'Bearer %s' % access_token
}

res = requests.post(url=instance_url+'/services/data/v42.0/composite/sobjects/',
                    data=body,
                    headers=headers)
print("res: %s " %  res.json())

This is the response I get:

res: [{'id': '0683X000009Xz5zQAC', 'success': True, 'errors': []}, {'id': '0683X000009Xz60QAC', 'success': True, 'errors': []}]

So everything looks super fine, but when I try to see or download the file from Salesforce is corrupt and I can't see it.

Could you please tell me what i'm doing wrong?

Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.