0

Today someone ask me a simple question And I thought it might be good to answer that here:

I want to know the type of content when I get the file with HTTP, How?

For example:

http.head(Uri.parse(myUrl)).then(
 (response) {
   if (response.statusCode == 200) {
     /*
         Now find the content type of myUrl
     */
   }
 },
);
  • 1
    Also see [Dart get extension from UInt8List](https://stackoverflow.com/q/66713893/), which might be more reliable than depending on the `content-type` value reported by the server. – jamesdlin Aug 02 '22 at 05:43

1 Answers1

0

As I said, this question is very simple

If you have this question, you can refer to this link and use the official documents

But if you are looking for the answer to this question in StackOverflow, the answer is:

http.head(Uri.parse(myUrl)).then(
 (response) {
   if (response.statusCode == 200) {
      print(response.headers['content-type']);
   }
 },
);

edit:

Thanks to jamesdlin Given that content-type is a value reported from the server, it is not reliable. An alternative and more reliable way is to use package:mime and the lookupMimeType function. like this:

http.get(Uri.parse(myUrl)).then(
 (response) {
   if (response.statusCode == 200) {
      final data = response.bodyBytes;
      final mime = lookupMimeType('', headerBytes: data);
      print(mime); // Print type of data
   }
 },
);