Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Form file - more complex form example #3686 #2

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 15 additions & 84 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions examples/form_file/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "form_file"
version = "0.1.0"
authors = ["Kenzi Connor <[email protected]>"]
edition = "2021"
license = "MIT OR Apache-2.0"

[dependencies]
base64 = "0.21.5"
gloo = "0.10"
gloo-console = "0.3.0"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["FormData", "HtmlFormElement"] }
yew = { path = "../../packages/yew", features = ["csr"] }
24 changes: 24 additions & 0 deletions examples/form_file/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Form /w File Upload Example

[![Demo](https://img.shields.io/website?label=demo&url=https%3A%2F%2Fexamples.yew.rs%2Fform_file)](https://examples.yew.rs/form_file)

This example shows some more comlicated interactions between file uploads, forms, and node_refs.

The file selector change disables the form button untill the file is done being processed, at which point it's stashed in App state untill the form is submitted and it's stored in the FileDetails.

## Concepts

Demonstrates reading from files in Yew with the help of [`gloo::file`](https://docs.rs/gloo-file/latest/gloo_file/).
Check the file_upload example for the simpler case of just uploading a file.

## Todo

- [] disabled form entirely by checking if there are readers left before allowing submit to proceed

## Running

Run this application with the trunk development server:

```bash
trunk serve --open
```
11 changes: 11 additions & 0 deletions examples/form_file/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Yew • Form w/ File Upload</title>

<link data-trunk rel="rust" />
</head>

<body></body>
</html>
135 changes: 135 additions & 0 deletions examples/form_file/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
use std::collections::HashMap;

use base64::{engine::general_purpose::STANDARD, Engine};
use gloo::file::{callbacks::FileReader, File, FileList};
use gloo_console::debug;
use web_sys::{File as RawFile, FormData, HtmlFormElement, HtmlInputElement};
use yew::prelude::*;

pub struct FileDetails {
name: String,
file_type: String,
data: Vec<u8>,
alt_text: String,
}

pub enum Msg {
Loaded(String, Vec<u8>),
Submit(SubmitEvent),
File(FileList),
}

pub struct App {
readers: HashMap<String, FileReader>,
files: Vec<FileDetails>,
button: NodeRef,
file_data: Vec<u8>,
}

impl Component for App {
type Message = Msg;
type Properties = ();

fn create(_ctx: &Context<Self>) -> Self {
Self {
readers: HashMap::default(),
files: Vec::default(),
button: NodeRef::default(),
file_data: Vec::default(),
}
}

fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::Loaded(name, data) => {
let submit = self.button.cast::<HtmlInputElement>().expect("button");
self.file_data = data;
submit.set_disabled(false);
self.readers.remove(&name);
}
Msg::File(files) => {
let submit = self.button.cast::<HtmlInputElement>().expect("button");
submit.set_disabled(true);

let file = files[0].clone();
let link = ctx.link().clone();
let name = file.name().clone();
let task = {
gloo::file::callbacks::read_as_bytes(&file, move |res| {
link.send_message(Msg::Loaded(name, res.expect("failed to read file")));
})
};
self.readers.insert(file.name(), task);
}
Msg::Submit(event) => {
debug!(event.clone());
event.prevent_default();
let form: HtmlFormElement = event.target_unchecked_into();
let form_data = FormData::new_with_form(&form).expect("form data");
let image_file = File::from(RawFile::from(form_data.get("file")));

let alt_text = form_data.get("alt-text").as_string().unwrap();
let name = image_file.name();
let data = self.file_data.clone();

let file_type = image_file.raw_mime_type();
self.files.push(FileDetails {
alt_text,
name,
data,
file_type,
});
self.file_data = Vec::default();
}
}
true
}

fn view(&self, ctx: &Context<Self>) -> Html {
html! {
<div id="wrapper">
<form onsubmit={ctx.link().callback(Msg::Submit)}>
<lable for="alt-text">{"Alt Text"}</lable>
<input id="alt-text" name="alt-text" />
<input
id="file"
name="file"
type="file"
accept="image/*"
multiple={false}
onchange={ctx.link().callback(move |e: Event| {
let input: HtmlInputElement = e.target_unchecked_into();
Msg::File(gloo::file::FileList::from(input.files().expect("file")))
})}
/>
<input ref={&self.button} type="submit"/>
</form>
<div id="preview-area">
{ for self.files.iter().map(Self::view_file) }
</div>
</div>
}
}
}

impl App {
fn view_file(file: &FileDetails) -> Html {
let src = format!(
"data:{};base64,{}",
file.file_type,
STANDARD.encode(&file.data)
);
html! {
<div class="preview-tile">
<p class="preview-name">{ format!("{}", file.name) }</p>
<div class="preview-media">
<img src={src} alt={file.alt_text.clone()}/>
</div>
</div>
}
}
}

fn main() {
yew::Renderer::<App>::new().render();
}