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.setTimeout(60000);//sets maximum timeout
    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;

  • can you more clearly indicate what the problem is and what are you trying to find? – Sebastian Kessel Aug 16 '19 at 18:48

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);
  • 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 '19 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 '19 at 20:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.