Matheus

Matheus

I am trying to create a form that saves some data, but I intend to include the possibility of adding a photo media. I did some research on the subject, and saw that they are implementing this new feature in liveview. I was wondering if there is any other way that I can create this type of event for the socket to understand the file upload? :smile:

Showing Posts 1 to 4

mindok

mindok

It isn’t really possible at the moment as far as I am aware.

There are some workarounds discussed here: Explore image uploads · Issue #104 · phoenixframework/phoenix_live_view · GitHub

I have it working quite nicely so if you can’t figure out a way forward based on the information there, let me know.

Matheus

Matheus OP

Thanks for the information :smile: .Can you explain to me how you managed to implement this event?

mindok

mindok

So between my comments (mindok) and those from montebrown in that github issue there should be quite a few pointers to implementing, but here’s the (messy) code…

Image upload controller - handles incoming images

defmodule AppWeb.UploadController do
  use AppWeb, :controller
  alias AppWeb.Context.Media

  def create(conn, %{"file" => %Plug.Upload{}=upload, "id" => raw_thing_id}) do
    {thing_id, ""} = Integer.parse(raw_thing_id)

    # You need code to store the file from the Plug.Upload struct here
    case Media.create_upload_from_plug_upload(upload, thing_id) do

      {:ok, upload}->
        put_flash(conn, :info, "file uploaded correctly")
        conn |> put_status(:created) |> json(%{id: upload.id})

      {:error, reason}->
        put_flash(conn, :error, "error upload file: #{inspect(reason)}")
        render(conn, "new.html")
    end
  end
end

Router entries

    resources "/uploads", UploadController, only: [:create] 

leex template with script embedded (haven’t got around to extracting js as yet, plus you will need some css from dropzone.js). And just to make it super nasty I inject an id into the script. In other places where I do file uploads I attach the JS to an element using liveview hooks and look up the id from a data attribute.

You may have to fight with CSRF tokens a bit too - they have changed in recent liveview versions

<div phx-update="ignore" class="dropzone dz-clickable" id="divtarget">
  <div class="dz-small dz-message d-flex flex-column">
    <span class="icon"><i class="fas fa-cloud-upload-alt fa-3x"></i></span>
    Drag &amp; Drop here or click
  </div>
</div>


<script src="/js/dropzone.js"></script>
<script src="/js/canvasToBlob.js"></script>
<script src="/js/cropper.js"></script>
<script>
Dropzone.options.divtarget = {
  paramName: "file", // The name that will be used to transfer the file
  url: '/uploads',
  maxFilesize: 10, // MB
  headers: {
    'x-csrf-token': '<%= @token %>'
  },
  init: function () {
    this.on("sending", function (fil, xhr, formData) {
      formData.append("id", '<%= @thing.id %>') 
    });
    this.on("complete", function (file) {
      this.removeFile(file);
    });
  },
  acceptedFiles: "image/jpeg, image/jpg, image/png, image/gif",
  transformFile: function (file, done) {
    var myDropZone = this;

    // Create the image editor overlay
    var editor = document.createElement('div');
    editor.style.position = 'fixed';
    editor.style.left = 0;
    editor.style.right = 0;
    editor.style.top = 0;
    editor.style.bottom = 0;
    editor.style.zIndex = 9999;
    editor.style.backgroundColor = '#000';

    // Create the confirm button
    var confirm = document.createElement('button');
    confirm.style.position = 'absolute';
    confirm.style.left = '10px';
    confirm.style.top = '10px';
    confirm.style.zIndex = 9999;
    confirm.textContent = 'Confirm';
    confirm.addEventListener('click', function () {

      // Get the canvas with image data from Cropper.js
      var canvas = cropper.getCroppedCanvas({});

      // Turn the canvas into a Blob (file object without a name)
      canvas.toBlob(function (blob) {

        // Update the image thumbnail with the new image data
        myDropZone.createThumbnail(
          blob,
          myDropZone.options.thumbnailWidth,
          myDropZone.options.thumbnailHeight,
          myDropZone.options.thumbnailMethod,
          false,
          function (dataURL) {

            // Update the Dropzone file thumbnail
            myDropZone.emit('thumbnail', file, dataURL);

            // Return modified file to dropzone
            done(blob);
          }
        );

      }, 'image/jpeg', 0.9);

      // Remove the editor from view
      editor.parentNode.removeChild(editor);

    });
    editor.appendChild(confirm);

    // Load the image
    var image = new Image();
    image.src = URL.createObjectURL(file);
    editor.appendChild(image);

    // Append the editor to the page
    document.body.appendChild(editor);

    // Create Cropper.js and pass image
    var cropper = new Cropper(image, {});
  }
};
</script>

D4no0

D4no0

Liveview has official support for file uploads these days: Uploads — Phoenix LiveView v1.2.5

— All posts loaded —

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
rahultumpala
Hello, I have an Elixir backend that implements a custom protocol over TCP. I want to load test the backend and assess the performance o...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews