function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SGupta1SGupta1 

How to upload a word document on box using rest API

 

 

Hi 

 

I want to upload  a word document  on Box( External Storage)  using Rest API calls  . 

 

Since i need blob as a valid UTF -8 string I am encoding first in base 64 using Encoding util class and then decoding it back as a blob and sending request using req.setbodyasblob() , 

 

I have used all the required parameters but I am getting below invalid request error .

 

{"type":"error","status":400,"code":"invalid_request_parameters","help_url":"http:\/\/developers.box.com\/docs\/#errors","message":"Invalid input parameters in request","request_id":"10130606285252db06ef703"}

 

can someone help ?

 

 

 

  public HTTPResponse uploadFile3()
{

   Document file =[Select Body, BodyLength, Id, Name, Type, ContentType From Document ];
      
      
        
       
        String p_fileName =file.Name+'.'+file.Type;
        String parent_id = '1121945745';
        String boundary = 'AaBbCcX30';
       
      
        
        
        String header = 'Content:\r\n--' + Boundary + '\r\n'+'Content-Disposition: form-data; name="files";filename="'+p_fileName+ '"\r\n'+ 'Content-Type:'+file.ContentType+'\r\n\r\n';
        header += '--' + Boundary +'\r\n'+'Content-Disposition: form-data; name="parent_id"'+'\r\n\r\n'+'0'+'\r\n' ;
         
        
       
        system.debug('header' +header);
        String footer = '\n--'+boundary+'--';
        system.debug('footer' +footer);
  // no trailing padding on header by adding ' ' before the last "\n\n" characters
  String headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\n\n'));
  system.debug('headerEncoded' +headerEncoded);
  //this ensures no trailing "=" padding
  while(headerEncoded.endsWith('='))
  {
   header+=' ';
   headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\n\n'));
   system.debug('headerEncoded@1' +headerEncoded);
  }
  //base64 encoded body
  String bodyEncoded = EncodingUtil.base64Encode(file.body);
  system.debug('bodyEncoded' +bodyEncoded);
  //base64 encoded footer
  String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
    system.debug('footerEncoded' +footerEncoded);
  Blob bodyBlob = null;
  //last encoded body bytes
  String last4Bytes = bodyEncoded.substring(bodyEncoded.length()-4,bodyEncoded.length());
  system.debug('last4Bytes' +last4Bytes);
  //if the last 4 bytes encoded base64 ends with the padding character (= or ==) then re-encode those bytes with the footer
  //to ensure the padding is added only at the end of the body
  if(last4Bytes.endsWith('='))
  {
   system.debug('inside last4 bytes');
   Blob  decoded4Bytes = EncodingUtil.base64Decode(last4Bytes);
   HttpRequest tmp = new HttpRequest();
   tmp.setBodyAsBlob(decoded4Bytes);
   String last4BytesFooter = tmp.getBody()+footer;   
   system.debug('inside last4 bytes@1'+last4BytesFooter);
   system.debug('inside last4 bytes@3'+EncodingUtil.base64Encode(Blob.valueOf(last4BytesFooter)));
   system.debug('inside last4 bytes@2'+ bodyEncoded.substring(0,bodyEncoded.length()-4));
  
   bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded.substring(0,bodyEncoded.length()-4)+EncodingUtil.base64Encode(Blob.valueOf(last4BytesFooter)));
   system.debug('bodyBlob' +bodyBlob);
  }
  else
  {
   bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);
  }
   
//  if(bodyBlob.size()>3000000)
//  { 
   //this a "public class CustomException extends Exception{}"
 //  throw new CustomException('File size limit is 3 MBytes');
 // }
   
    Http h = new Http();
        HttpRequest req = new HttpRequest();
        string sUrl = 'https://upload.box.com/api/2.0/files/content';
        req.setHeader('Authorization', 'Bearer ' + accessToken);
        req.setHeader('Content-Type','multipart/form-data;boundary='+boundary);
        req.setHeader('Content-Encoding','base64');
      
        req.setEndpoint(sUrl);
        
        req.setMethod('POST');
        req.setBodyAsBlob(bodyBlob);
        System.debug('LAST ENCODING: '+EncodingUtil.base64Encode(req.getBodyAsBlob()));
  
   HttpResponse res;
        if(!Test.isRunningTest()){
            res = h.send(req);
        }
        else{
             res = new HttpResponse();
        }
        valuetoShow = 'Get Doc: ' + res.getBody(); 
        return res;
      

 

Sure@DreamSure@Dream
Hi SGupta1,


Are you able to complete this?.

I am tryign to upload a file from my desktop to box.com, by connecting to box.com via salesforce(oAuth).

Could  you please help me with this?

Thanks.
vanathi vvanathi v

Hi SGupta1 and Sure@Dream,
       Even am trying with the Same are u people able to complete it??... I can upload a file to box but i need to view it in png format so we need to pass non_svg = true. If u guys had success with the header part Plz let me know. Its very urgent.
Thanks.
       
Hanumantha Rao MuddanaHanumantha Rao Muddana
Box has appExchange product. You can try it.
https://appexchange.salesforce.com/listingDetail?listingId=a0N30000001qNeKEAU
Sunil PalSunil Pal
Hi All,
I dont know whether this issue is fixed or not but here I am able to upload the file by using my code please check once and let us know the status.
===================================
public String uploadFileToBox(String strFolderId,Document file,String token)
     {
        String boundary = '----------------------------741e90d31eff';
        String header = '--'+boundary+'\nContent-Disposition: form-data; name="file"; filename="'+file.name+'";\nContent-Type: multipart/form-data;'+'\nnon-svg='+True;
        String footer = '--'+boundary+'--';             
        String headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));
        HttpResponse res;
        String strFileId;
      
        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 = bodyEncoded.substring(bodyEncoded.length()-4,bodyEncoded.length());
        
        // GW: replacement section to get rid of padding without corrupting data
        if(last4Bytes.endsWith('==')) 
        {
              last4Bytes = last4Bytes.substring(0,2) + '0K';
            bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
            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;
            footer = '\n' + footer;
            String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
            bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);              
        } 
        
        else 
        {
            footer = '\r\n' + footer;
            String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
            bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);  
        }
    
        String sUrl = 'https://upload.box.com/api/2.0/files/content?parent_id='+strFolderId;
          HttpRequest req = new HttpRequest();
      
          req.setHeader('Content-Type','multipart/form-data;non_svg='+True+';boundary='+boundary);

          req.setMethod('POST');
          req.setEndpoint(sUrl);
         req.setBodyAsBlob(bodyBlob);
          req.setTimeout(60000);
          req.setHeader('Authorization', 'Bearer '+token);
          req.setHeader('Content-Length',String.valueof(req.getBodyAsBlob().size()));
      
          Http http = new Http();
          
          system.debug('*****size****'+req.getBodyAsBlob().size());
          
        if(Test.isRunningTest()) {
                
                // Create a fake response
            res = new HttpResponse();
            res.setStatusCode(201);
        }
        else {
            
               res = http.send(req);
        }
      
        
    }
    
=================

Thanks,
Sunil
 
veera lankaveera lanka
Hi Sunil,

How to test the above code in developer console? Below are the values i passed, but i am not sure how to pass the value to attachment file. Can you please tell me how to pass the values.

BoxHelper.uploadFile('0',  " Here I need to pass the attachment value. How to do that? "  , 'dSsSm8ZPqzuqUJAb8Qdpi6ty1to7WL39');

Thanks,
Veera