workflow_dom/
download.rs

1use crate::result::Result;
2use crate::utils::*;
3use js_sys::{Array, Uint8Array};
4use web_sys::{Blob, MouseEvent, Url};
5
6pub fn data(filename: &str, content: &[u8], mime: &str) -> Result<()> {
7    let document = document();
8    let body = body()?;
9
10    let args = Array::new_with_length(1);
11    args.set(0, unsafe { Uint8Array::view(content).into() });
12    let options = web_sys::BlobPropertyBag::new();
13    options.set_type(mime);
14    let blob = Blob::new_with_u8_array_sequence_and_options(&args, &options)?;
15    let url = Url::create_object_url_with_blob(&blob)?;
16
17    let el = document.create_element("a").unwrap();
18    el.set_attribute("href", filename).unwrap();
19    el.set_attribute("download", &url).unwrap();
20
21    body.append_child(&el).unwrap();
22
23    let event = MouseEvent::new("click").unwrap();
24    el.dispatch_event(&event).unwrap();
25
26    body.remove_child(&el).unwrap();
27
28    Url::revoke_object_url(&url)?;
29
30    Ok(())
31}
32
33pub fn text(filename: &str, content: &str) -> Result<()> {
34    data(filename, content.as_bytes(), "text/plain")
35}