redux-form和elixir/phoenix的文件附件作为后端API(序列化问题)

Mih*_*kov 8 file elixir reactjs redux redux-form

product我的elixir/phoenix后端有两个控制器.第一 - API端点(pipe_through :api)和第二个控制器piping through :browser:

# router.ex
scope "/api", SecretApp.Api, as: :api do
  pipe_through :api

  resources "products", ProductController, only: [:create, :index]
end

scope "/", SecretApp do
  pipe_through :browser # Use the default browser stack

  resources "products", ProductController, only: [:new, :create, :index]
end
Run Code Online (Sandbox Code Playgroud)

ProductController处理来自elixir表单助手生成的表单的请求,并接受一些文件附件.一切都很好.这是由此操作处理的create action和params:

def create(conn, %{"product" => product_params}) do
  changeset = Product.changeset(%Product{}, product_params)

  case Repo.insert(changeset) do
    {:ok, _product} ->
      conn
      |> put_flash(:info, "Product created successfully.")
      |> redirect(to: product_path(conn, :index))
    {:error, changeset} ->
      render(conn, "new.html", changeset: changeset)
  end
end
Run Code Online (Sandbox Code Playgroud)

来自日志的params(我使用arc来处理elixir代码中的图像上传)

[debug] Processing by SecretApp.ProductController.create/2
  Parameters: %{"_csrf_token" => "Zl81JgdhIQ8GG2c+ei0WCQ9hTjI+AAAA0fwto+HMdQ7S7OCsLQ9Trg==", "_utf8" => "?", 
              "product" => %{"description" => "description_name", 
                "image" => %Plug.Upload{content_type: "image/png", 
                  filename: "wallpaper-466648.png", 
                  path: "/tmp/plug-1460/multipart-754282-298907-1"}, 
                "name" => "product_name", "price" => "100"}}
  Pipelines: [:browser]
Run Code Online (Sandbox Code Playgroud)

Api.ProductController处理来自redux-from的请求.这是action,view和params,由这个动作处理:

# action in controller
def create(conn, %{"product" => product_params}) do
  changeset = Product.changeset(%Product{}, product_params)

  case Repo.insert(changeset) do
    {:ok, _product} ->
      conn
      |> render("index.json", status: :ok)
    {:error, changeset} ->
      conn
      |> put_status(:unprocessable_entity)
      |> render("error.json", changeset: changeset)
  end
end

# product_view.ex
def render("index.json", resp=%{status: status}) do
  %{status: status}
end

def render("error.json", %{changeset: changeset}) do
  errors = Enum.into(changeset.errors, %{})

  %{
    errors: errors
  }
end

[info] POST /api/products/
[debug] Processing by SecretApp.Api.ProductController.create/2
  Parameters: %{"product" => %{"description" => "product_description", "image" => "wallpaper-466648.png", "name" => "product_name", "price" => "100"}}
  Pipelines: [:api]
[info] Sent 422 in 167ms
Run Code Online (Sandbox Code Playgroud)

创建操作失败,状态为422,因为无法使用这些参数保存图像.我的问题是我无法从后端代码访问图像,我只在我的JS代码中将它作为FileList对象.我不明白如何将图像传递给后端代码.以下是此附件在我的JS代码(FileList,包含有关上载图像的信息)中的表示方式.

value:FileList
  0: File
    lastModified: 1381593256801
    lastModifiedDate: Sat Oct 12 2013 18:54:16 GMT+0300 
    name: "wallpaper-466648.png"
    size: 1787293
    type: "image/png"
    webkitRelativePath: ""
Run Code Online (Sandbox Code Playgroud)

我只有WebkitRelativePath(如果第一个控制器我有图像路径:"/ tmp/plug-1460/multipart-754282-298907-1")我不知道我该怎么处理这个JS对象以及如何访问由此JS对象表示的真实图像(这是关于文件上载的redux-form参考).

你可以帮帮我吗?如何向elixir解释如何找到图像?我只是想使用JS代码向我的后端提交文件附件(因为有很多有趣的异步验证功能等).

这是一个完整的应用程序的链接,如果它可能会有所帮助

Mih*_*kov 3

最后我设法解决了这个问题。解决方案是正确序列化redux-form提交的参数。

这是我的 redux 表单,请求的起点:

// product_form.js

import React, { PropTypes } from 'react';
import {reduxForm} from 'redux-form';

class ProductForm extends React.Component {
  static propTypes = {
    fields: PropTypes.object.isRequired,
    handleSubmit: PropTypes.func.isRequired,
    error: PropTypes.string,
    resetForm: PropTypes.func.isRequired,
    submitting: PropTypes.bool.isRequired
  };

  render() {
    const {fields: {name, description, price, image}, handleSubmit, resetForm, submitting, error} = this.props;

    return (
      <div className="product_form">
        <div className="inner">
          <form onSubmit={handleSubmit} encType="multipart/form-data">
            <div className="form-group">
              <label className="control-label"> Name </label>
              <input type="text" className="form-control" {...name} />
              {name.touched && name.error && <div className="col-xs-3 help-block">{name.error}</div>}
            </div>

            <div className="form-group">
              <label className="control-label"> Description </label>
              <input type="textarea" className="form-control" {...description} />
              {description.touched && description.error && <div className="col-xs-3 help-block">{description.error}</div>}
            </div>

            <div className="form-group">
              <label className="control-label"> Price </label>
              <input type="number" step="any" className="form-control" {...price} />
              {price.touched && price.error && <div className="col-xs-3 help-block">{price.error}</div>}
            </div>

            <div className="form-group">
              <label className="control-label"> Image </label>
              <input type="file" className="form-control" {...image} value={ null } />
              {image.touched && image.error && <div className="col-xs-3 help-block">{image.error}</div>}
            </div>

            <div className="form-group">
              <button type="submit" className="btn btn-primary" >Submit</button>
            </div>
          </form>
        </div>
      </div>
    );
  }
}

ProductForm = reduxForm({
  form: 'new_product_form',
  fields: ['name', 'description', 'price', 'image']
})(ProductForm);

export default ProductForm;
Run Code Online (Sandbox Code Playgroud)

handleSubmit用户按下“提交”按钮后,此表单将以下参数传递给函数

# values variable
Object {name: "1", description: "2", price: "3", image: FileList}

# where image value is 
value:FileList
  0: File
    lastModified: 1381593256801
    lastModifiedDate: Sat Oct 12 2013 18:54:16 GMT+0300 
    name: "wallpaper-466648.png"
    size: 1787293
    type: "image/png"
    webkitRelativePath: ""
Run Code Online (Sandbox Code Playgroud)

为了将这些参数传递给后端,我使用FormData Web API使用 isomorphic-fetch npm 模块发送文件上传请求

这是实现这一技巧的代码:

// product_form_container.js (where form submit processed, see _handleSubmit function)

import React                   from 'react';
import ProductForm             from '../components/product_form';
import { Link }                from 'react-router';
import { connect }             from 'react-redux';
import Actions                 from '../actions/products';
import * as form_actions            from 'redux-form';
import {httpGet, httpPost, httpPostForm} from '../utils';

class ProductFormContainer extends React.Component {
  _handleSubmit(values) {
    return new Promise((resolve, reject) => {
      let form_data = new FormData();

      Object.keys(values).forEach((key) => {
        if (values[key] instanceof FileList) {
          form_data.append(`product[${key}]`, values[key][0], values[key][0].name);
        } else {
          form_data.append(`product[${key}]`, values[key]);
        }
      });

      httpPostForm(`/api/products/`, form_data)
      .then((response) => {
        resolve();
      })
      .catch((error) => {
        error.response.json()
        .then((json) => {
          let responce = {};
          Object.keys(json.errors).map((key) => {
            Object.assign(responce, {[key] : json.errors[key]});
          });

          if (json.errors) {
            reject({...responce, _error: 'Login failed!'});
          } else {
            reject({_error: 'Something went wrong!'});
          };
        });
      });
    });
  }

  render() {
    const { products } = this.props;

    return (
      <div>
        <h2> New product </h2>
        <ProductForm title="Add product" onSubmit={::this._handleSubmit} />

        <Link to='/admin/products'> Back </Link>
      </div>
    );
  }
}

export default connect()(ProductFormContainer);
Run Code Online (Sandbox Code Playgroud)

fetchhttpPostForm的包装器在哪里:

export function httpPostForm(url, data) {
  return fetch(url, {
    method: 'post',
    headers: {
      'Accept': 'application/json'
    },
    body: data,
  })
  .then(checkStatus)
  .then(parseJSON);
}
Run Code Online (Sandbox Code Playgroud)

就是这样。我的 Elixir 代码中没有任何需要修复的内容,Api.ProductController保持不变(请参阅最初的帖子)。但现在它收到带有以下参数的请求:

[info] POST /api/products/
[debug] Processing by SecretApp.Api.ProductController.create/2
  Parameters: %{"product" => %{
                "description" => "2", 
                "image" => %Plug.Upload{
                  content_type: "image/jpeg",
                  filename: "monkey_in_jungle-t3.jpg", 
                  path: "/tmp/plug-1461/multipart-853391-603088-1"
                }, 
               "name" => "1", 
               "price" => "3"}}
  Pipelines: [:api]
Run Code Online (Sandbox Code Playgroud)

非常感谢每个试图帮助我的人。希望这可以帮助那些遇到类似序列化问题的人。