Http Request with multipart/form-data Salesforce upload file.



public void upload(String boundary,string filename,boolean file_body) {


    String header = '--' + boundary + '\r\n' +
                        + 'Content-Type: application/octet-stream\r\n'+
                        + 'Content-Disposition: form-data; name="file";filename="' + filename +'"';

        String headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header + '\r\n\r\n'));

        String footer = '--' + boundary + '--';

        while(headerEncoded.endsWith('='))
        {
            header += ' ';
            headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));
        }

        String bodyEncoded = EncodingUtil.base64Encode(file_body);
       
        Blob bodyBlob = null;

        String last4Bytes = fileContent.substring(bodyEncoded.length()-4,bodyEncoded.length());
        System.debug('----->last4Bytes: '  + last4Bytes );

        if(last4Bytes.endsWith('==')) {
            last4Bytes = last4Bytes.substring(0,2) + '0K';
            bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
            // We have appended the \r\n to the Blob, so leave footer as it is.
            String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
            bodyBlob = EncodingUtil.base64Decode(headerEncoded + bodyEncoded + footerEncoded);
        } else if(last4Bytes.endsWith('=')) {
            last4Bytes = last4Bytes.substring(0,3) + 'N';
            bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
            // We have appended the CR e.g. \r, still need to prepend the line feed to the footer
            footer = '\n' + footer;
            String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
            bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);            

        } else {
            // Prepend the CR LF to the footer
            footer = '\r\n' + footer;
            String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
            bodyBlob = EncodingUtil.base64Decode(headerEncoded + bodyEncoded + footerEncoded);
        }

        System.debug('---> Body: ' + bodyBlob);
        HTTPRequest req= new HttpRequest();
        req.setendpoint('https://upload.box.com/api/2.0/files/content');
        req.setmethod('POST');
        req.setHeader('Authorization','Bearer ' + creds.Access_Token__c);
        req.setHeader('Content-Type','multipart/form-data; boundary='+boundary);
        req.setBodyAsBlob(bodyBlob);
        System.debug(' res -----> :' + req.getBody());
        Http p = new Http();
        HttpResponse res= new HttpResponse();
        res = p.send( Req );

}


Creadit to: http://blog.enree.co/2013/01/salesforce-apex-post-mutipartform-data.html

6 comments:

  1. Thanks bro, i was stuck in this multipart so long. great content

    ReplyDelete
  2. Hi, I just wanna know how I can send multiple value in form-data, for example:
    I need to send XML but also I need to send HASH value (TEXT), I this moment
    I can send XMl but hash value not and all example on internet anly send one value..!!

    ReplyDelete
    Replies
    1. HI
      Did you have any solution for multiple file post in one request ?
      Please help

      Thanks

      Delete
  3. HI
    Did you have any solution for multiple file post in one request ?
    Please help

    Thanks

    ReplyDelete
    Replies
    1. @Sirai, Please use below format to send multiple files

      ----BOUNDARY_STRING
      Content-Disposition: form-data; name="email";

      test@test.com
      ----BOUNDARY_STRING
      Content-Disposition: form-data; name="upload_test"; filename="myfile.pdf"
      Content-Type: text/octet-stream

      ENCRYPTED_FILE_CONTENT
      ----BOUNDARY_STRING

      Apologies for delay.

      Delete
  4. Hey,
    Can anyone please help me to send an request in the below format through APEX?
    PLEASE HELP!!!!!!!

    Content-Type: multipart/form-data; boundary="----=_Part_2_23463483.1505914860687"
    Content-Transfer-Encoding: binary
    Content-Disposition: form-data; name="metadata"
    Authorization: Bearer XXXXXXXXXXXXXXXXXXXXX
    Transfer-Encoding: chunked

    ------=_Part_2_23463483.1505914860687
    Content-Type: multipart/form-data
    Content-Transfer-Encoding: 8bit

    {
    "documentVo": {
    "userId": "P52DJDOE",
    "busFuncCd": "12",
    "busFuncDocType": "ACHA",
    "imageVo": {
    "fileFormat": "PDF"
    },
    "indexValueBlock": [{
    "indexName": "AcctNum",
    "indexVal": "52D000000"
    }, {
    "indexName": "DocNme",
    "indexVal": "ACH AUTHORIZATION FORMS"
    }
    ]
    }
    }

    ------=_Part_2_23463483.1505914860687
    Content-Type: application/octet-stream; name=
    Content-Transfer-Encoding: binary
    Content-Disposition: form-data; name="document"; filename=""

    %PDF-1.3
    %����
    14 0 obj
    <>
    endobj

    20 0 obj
    <>/Filter/FlateDecode/ID[<91E5C4B1B98F04438E771EAE3C0EA4E1><91E5C4B1B98F04438E771EAE3C0EA4E1>]/Index[14 9]/Info 13 0 R/Length 44/Prev 11673/Root 15 0 R/Size 23/Type/XRef/W[1 2 0]>>stream
    h�bbd`b`�fb`�cb`l[1]�?@z& ÃÂÂ??x&F�yL��


    PLEASE HELP!!!!!!!

    ReplyDelete