Skip to content

Instantly share code, notes, and snippets.

@eduardodeoh
Last active July 6, 2020 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eduardodeoh/afe222facb3eaf71b87a74baf1a1cf98 to your computer and use it in GitHub Desktop.
Save eduardodeoh/afe222facb3eaf71b87a74baf1a1cf98 to your computer and use it in GitHub Desktop.
LiveView Upload example
#router.ex
# Add specific plug pipeline to router.ex
pipeline :browser_upload do
plug(Plug.Logger)
plug(:accepts, ["html"])
plug(:fetch_session)
plug(:fetch_live_flash)
plug(:put_secure_browser_headers)
end
# Add route
scope "/uploads", FrameworkWeb do
pipe_through([:browser_upload])
post("/", UploadsController, :create)
end
# controller
defmodule FrameworkWeb.UploadsController do
use FrameworkWeb, :controller
def create(conn, params) do
content =
params["file"].path
|> File.stream!()
|> Stream.map(& &1)
|> Enum.reduce("", fn line, acc -> acc <> line end)
send_resp(conn, 200, content)
end
end
# upload.js
const jQuery = require("jquery");
export function UploadFile(formData, url) {
return jQuery.ajax({
type: "POST",
enctype: "multipart/form-data",
url: url,
data: formData,
processData: false, //IMPORTANT!
cache: false,
contentType: false
});
}
# phx_hook.js
import { UploadFile } from "./upload";
Hooks.UploadFile = {
mounted() {
this.el.addEventListener("change", (e) => {
const formData = new FormData();
const fileName = this.el.files[0].name;
formData.set("file", this.el.files[0]);
const hook = this;
let upload_process = UploadFile(formData, "/uploads/your_url");
upload_process
.done(function (response_data) {
hook.pushEvent("file-uploaded", {
"file-content": response_data,
"file-name": fileName
});
})
.fail(function (response_data) {
hook.pushEvent("file-uploaded", { "error": response_data });
});
});
},
};
#.html.leex
<%= file_input(:form_upload, :file, phx_hook: "UploadFile") %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment