0

I am using apex code to get file from url and able to insert it as attachment. I would like to know file name as well while insert ?

When I open link in chrome it save the file with file name.

public void getAndAttachFile(String recId, String fileId) {


    // Instantiate a new http object
    Http h = new Http();
    // Instantiate a new HTTP request, specify the method (GET) as well as the endpoint
    HttpRequest req = new HttpRequest();
    req.setEndpoint('https://secure.basecone.com/Lookup/Download?externalId='+fileId);
    req.setTimeout(60000);//sets maximum timeout
    req.setMethod('GET');
    HttpResponse res = h.send(req);
    Blob body = res.getBodyAsBlob();

    // **Here I want to set actual file name in Name field**
    Attachment att = new Attachment(Name = fileId, Body = body, ParentId=recId);
    insert att;

}
1
  • can you more clearly indicate what the problem is and what are you trying to find? Aug 16, 2019 at 18:48

1 Answer 1

4

This information is contained in the response header. A bit of parsing is required:

String fileName = 'default name';
Pattern p = Pattern.compile('.+filename="(.+?)".*');
String contentDisposition = res.getHeader('Content-Disposition');
if(contentDisposition != null) {
  Matcher m = p.matcher(contentDisposition);
  if(m.find()) {
    fileName = m.group(1);
  }
}
2
  • It works for me, however I need to change RegEx. It give me an idea from where to fetch such details. Thanks! :)
    – Kritik
    Aug 16, 2019 at 20:14
  • 1
    @Kritik I typed it out on my phone, so was untested. If you'd like, please feel free to edit this answer to include the correct regex.
    – sfdcfox
    Aug 16, 2019 at 20:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .