skip to Main Content

I am downloading a file from a server with a GET request. Like this.

import 'package:http/http.dart' as http;

    final http.Response response = await http.get(uri, headers: headers);
    if (response.isOk()) {
      response.headers.forEach((key, value) {
        print('key = $key; value = $value');
      });

      final Uint8List bytes = response.bodyBytes;

      AnchorElement(href: "$contentPrefix${base64Encode(bytes)}")
        ..setAttribute("download", "file.xlsx")
        ..click();
    } else {
      print('report request status code is ${response.statusCode}');
    }

I need to know the file name.

The file name is contained in the content-disposition header, in different encodings. But it is not in http.Response.headers.
How to extract filename in UTF-8 encoding?

enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    Based on Richard Heap's comment.

    1. Add header Access-Control-Expose-Headers in server response

    In my case its Java server:

            return Response
                    .ok(excelFile)
                    .header(HttpHeaders.CONTENT_DISPOSITION, contentHeader)
                    .header("Access-Control-Expose-Headers", HttpHeaders.CONTENT_DISPOSITION)
                    .build();
    
    1. Parse filename from Content-Disposition header:
      String? tryDecodeFileName(http.Response response) {
        final String? headerValue = response.headers['content-disposition'];
        if (headerValue != null) {
          const String pattern = 'filename*=utf-8' '';
          return Uri.decodeFull(headerValue
              .substring(headerValue.indexOf(pattern) + pattern.length + 2));
        }
        return null;
      }
    

    Im my case header value starts with: attachment;filename="report.xlsx";filename*=utf-8''.

    More info about filename in content disposition header.


  2. Only certain HTTP response headers are available to cross site XHR requests, as would be the case in a Flutter Web application making a request from a server that didn’t launch it. Such a request firstly needs the relevant CORS headers, but if you want to be able to access one of the non-default response headers, also needs the Access-Control-Expose-Headers header.

    The CORS-safelisted response headers are: Cache-Control, Content-Language, Content-Length, Content-Type, Expires, Last-Modified, Pragma. Since Content-Disposition isn’t a safelisted header, your server will need to emit:

    Access-Control-Expose-Headers: Content-Disposition
    

    The Content-Disposition header will then appear in response.headers.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search