代码之家  ›  专栏  ›  技术社区  ›  Tessy Thomas

使用Elixir中的Acr将文件上载到本地

  •  2
  • Tessy Thomas  · 技术社区  · 6 年前

    我用的是弧。定义( https://github.com/stavro/arc )用于将图像上载到本地存储。

    我的文件\ u service.ex如下:

    defmodule MyApp.FileService do
      use Arc.Definition
      use Arc.Ecto.Definition
    
      @image_types ~w(.jpg .jpeg .png .gif)
      @versions [:original]
      @default_filename "image.png"
    
      @heights %{
        medium: 400
      }
    
      @widths %{
        medium: 400
      }
    
      def __storage, do: Arc.Storage.Local
    
      def upload_image(%Plug.Upload{} = image, resource_type, resource_id) do
        store({%Plug.Upload{path: image.path, filename: @default_filename},
          %{resource_type: resource_type, resource_id: resource_id}})
      end
    
      def upload_base64_image(base64_image, resource_type, resource_id) do
        store({%{filename: @default_filename, binary: base64_image_to_binary(base64_image)}})
      end 
    
      def delete_file(image_url, resource) do
        delete({image_url, resource})
      end
    
      defp base64_image_to_binary("data:image/" <> rest) do
        rest
        |> String.replace("\n", "")
        |> String.split(",")
        |> Enum.at(1)
        |> Base.decode64!
      end
      defp base64_image_to_binary(base64_image) do
        base64_image
        |> String.replace("\n", "")
        |> Base.decode64!
      end
    end
    

    (arc)lib/arc/actions/store.ex:8:arc.actions.store.store(MyApp.FileService,{%{binary:<&书信电报;255, 216, 255, 225, 3, 48, 69, 120, 105, 102, 0, 0, 73, 73, 42, 0, 8, 0, 0, 0, 58, 0, 50, 1, 2, 0, 20, 0, 0, 0, 198, 2, 0, 0, 15, 1, 2, 0, 10, 0, 0, 0,218,2,0,0,1,1,…>>,文件名:“image.png”})

    任何人,请帮忙?

    1 回复  |  直到 6 年前
        1
  •  1
  •   chris    6 年前

    你的代码

     def upload_base64_image(base64_image, resource_type, resource_id) do
        store({%{filename: @default_filename, binary: base64_image_to_binary(base64_image)}})
      end 
    

    store 使用错误。

    它只接受 tuple(file, scope) filepath(map) .

    所以应该是: store(%{filename: @default_filename, binary: base64_image_to_binary(base64_image)}) .

    参见github的示例:

    # Store a file from a connection body
    {:ok, data, _conn} = Plug.Conn.read_body(conn)
    Avatar.store(%{filename: "file.png", binary: data})
    

      def store(definition, {file, scope}) when is_binary(file) or is_map(file) do
        put(definition, {Arc.File.new(file), scope})
      end
    
      def store(definition, filepath) when is_binary(filepath) or is_map(filepath) do
        store(definition, {filepath, nil})
      end