简体   繁体   中英

How to convert Base64 to HTML?

I need to convert Base64 to HTML in Flutter, but it fails.

This is my HTML encoded Base64 string:

"PGh0bWw+DQo8aGVhZD4NCiAgPHRpdGxlPlRpdGxlIG9mIHRoZSBkb2N1bWVudDwvdGl0bGU+DQo8L2hlYWQ+DQoNCjxib2R5Pg0KICA8aDE+VGhpcyBpcyBhIGhlYWRpbmc8L2gxPg0KICA8cD5UaGlzIGlzIGEgcGFyYWdyYXBoLjwvcD4NCjwvYm9keT4NCg0KPC9odG1sPg=="

I already try to decode but the output format just an array of numbers.

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_html/flutter_html.dart';

var decoded = base64.decode(
      "PGh0bWw+DQo8aGVhZD4NCiAgPHRpdGxlPlRpdGxlIG9mIHRoZSBkb2N1bWVudDwvdGl0bGU+DQo8L2hlYWQ+DQoNCjxib2R5Pg0KICA8aDE+VGhpcyBpcyBhIGhlYWRpbmc8L2gxPg0KICA8cD5UaGlzIGlzIGEgcGFyYWdyYXBoLjwvcD4NCjwvYm9keT4NCg0KPC9odG1sPg==");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: HeaderMenu(
        title: Text(
          'Base64 to HTML',
          style: TextStyle(color: Colors.black, fontWeight: FontWeight.w600),
        ),
        isBack: true,
        icon: [],
        isCenter: true,
      ),
      body: Column(
        children: [
          Html(data: decoded.toString()),
        ],
      ),
    );
  }

The purpose of encoding something to base64 is to convert binary data to ASCII text. It doesn't make a lot of sense to base64-encode HTML, which is already text. (But I suppose maybe it was base64-encoded as some overzealous way of performing data sanitization.)

Anyway, when you decode a base64 string, the result is expected to binary data. To treat that sequence of bytes as a string, you will need to perform an additional decoding step to specify how those bytes should be interpreted: as ASCII text? as UTF-8-encoded text? UTF-16? UTF-32?

In your case, your base64 string appears to be UTF-8:

import 'dart:convert';

void main() {
  var base64String =
      "PGh0bWw+DQo8aGVhZD4NCiAgPHRpdGxlPlRpdGxlIG9mIHRoZSBkb2N1bWVudDwvdGl0bGU+DQo8L2hlYWQ+DQoNCjxib2R5Pg0KICA8aDE+VGhpcyBpcyBhIGhlYWRpbmc8L2gxPg0KICA8cD5UaGlzIGlzIGEgcGFyYWdyYXBoLjwvcD4NCjwvYm9keT4NCg0KPC9odG1sPg==";
  var bytes = base64.decode(base64String);
  var decoded = utf8.decode(bytes);
  print(decoded);
}

prints:

<html>
<head>
  <title>Title of the document</title>
</head>

<body>
  <h1>This is a heading</h1>
  <p>This is a paragraph.</p>
</body>

</html>

Using ascii.decode also would work in your particular case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM