Search code examples
linuxvala

Vala Image Base64 in Web


I would like to know if in Vala (Soup.Server) I can visualize an image that I have as a string in base64 format?

private static void default_handler (Soup.Server server,Soup.Message msg,string path,GLib.HashTable? query,Soup.ClientContext client) {

var imgStr = (string) Base64.decode ("iVBORw0...."); msg.set_response("image/jpeg",Soup.MemoryUse.COPY,"%s".printf(imgStr).data);

}1


Solution

  • solution

    void handle_static_file(Soup.Server server, Soup.Message message,
                string path, HashTable? query, Soup.ClientContext context) {
            server.pause_message(message);
            handle_static_file_async.begin(server, message, path, query, context);
        }
    
        async void handle_static_file_async(Soup.Server server,
                Soup.Message message, string path, HashTable? query,
                Soup.ClientContext context) {
            if (path == "/" || path == "") {
                path = "index.html";
            }
            var file = File.new_for_path("static/" + path);
            try {
                var info = yield file.query_info_async("*", FileQueryInfoFlags.NONE);
                var io = yield file.read_async();
                Bytes data;
                while ((data = yield io.read_bytes_async((size_t)info.get_size())).length > 0) {
                    message.response_body.append(Soup.MemoryUse.COPY,
                        data.get_data());
                }
                string content_type = info.get_content_type();
                message.set_status(Soup.Status.OK);
                message.response_headers.set_content_type(content_type, null);
            } catch (IOError.NOT_FOUND e) {
                message.set_status(404);
                message.set_response("text/plain", Soup.MemoryUse.COPY,
                    ("File " + file.get_path() + " does not exist.").data);
            } catch (Error e) {
                if (debug) {
                    stderr.printf("Failed to read file %s: %s\n", file.get_path(),
                        e.message);
                }
                message.set_status(500);
                message.set_response("text/plain", Soup.MemoryUse.COPY,
                    e.message.data);
            } finally {
                server.unpause_message(message);
            }
        }