Showing posts with label upload file. Show all posts
Showing posts with label upload file. Show all posts

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