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
Sumant Kuchipu 1Sumant Kuchipu 1 

How to open/download a file returned from HttpResponse (from BOX) in Apex?

Hi,

I'm trying to open/download a file returned from box.

when we click on a "Cleck Me" link, it calls the VF page and calls the Apex .. but I'm not sure how to open/download page from apex
Image and code are below.

User-added image

VF page:
<apex:page controller="BoxController" action="{!fileOpen}">

</apex:page>

Apex code:
 
try{
            String bFileId=String.valueof(ApexPages.CurrentPage().getparameters().get('bFileID'));

            String aToken = api.getAccessToken();
            if(bFileId!=null && bFileId!=''){
                String endPointURLToViewFile='https://api.box.com/2.0/files/'+bFileId+'/content';
                HttpRequest req = new HttpRequest();
                req.setEndpoint(endPointURLToViewFile);
                req.setMethod('GET');
                req.setHeader('Authorization', 'Bearer ' + aToken);
                req.setHeader('Content-Type','application/json');
                req.setHeader('Accept','application/json');
                req.setTimeout(120000);
                Http http = new Http();
                HTTPResponse res = http.send(req);
                
                String downloadURL=res.getHeader('Location');

            }
        }catch (Exception e){
            System.debug(' **** File Download Exceptions '+e);
        }
    }

Here I can get "downloadURL" but I don't know how to call this URL to opan/download with that URL.
Could someone please help me on this? 

Thanks,
Sumant K
 
Sumant Kuchipu 1Sumant Kuchipu 1
I was able to down the file with the PageRedirect ...Almost solved my problem
 
PageReference page;
.
.
String downloadURL=res.getHeader('Location');
page = new PageReference(downloadURL);
page.setRedirect(true);
return page;

But when I click the link, a new page if opening and downloading the file.. is there a way to open file directly? or download on the same page? 
I think in Formula field I use to call VF and from there invoking apex controller (the above code) .. my be that is why its opening a new page .. Im not sure please correct me and give solution ..

Best