gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:24:30 25 4
gpt4 key购买 nike

我的 elixir/phoenix 后端中有两个 product Controller 。第一个 - API 端点 (pipe_through :api) 和第二个 Controller 通过 :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

ProductController 处理来自 elixir 表单助手生成的表单的请求并接受一些文件附件。一切都很好。这是创建操作和该操作处理的参数:

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

来自日志的参数(我正在使用 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]

Api.ProductController 处理来自 redux-from 的请求。这是由该操作处理的操作、 View 和参数:

# 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

创建操作失败,状态为 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: ""

我只有 WebkitRelativePath (如果使用第一个 Controller ,我有图像路径:“/tmp/plug-1460/multipart-754282-298907-1”),我不知道我可以用这个 JS 对象做什么以及如何访问这个JS对象所代表的真实图像(这里有一个关于文件上传的redux-form reference)。

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

这里是完整的 app 的链接如果有帮助的话

最佳答案

终于我成功解决了这个问题。解决方案是正确序列化 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;

当用户按下“提交”按钮后,此表单将以下参数传递给函数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: ""

为了将这些参数传递到后端,我使用 FormData Web APIfile-upload request using isomorphic-fetch npm module

下面的代码实现了这一点:

// 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);

其中 httpPostFormfetch 的包装器:

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

就是这样。我的 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]

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

关于redux-form 和 Elixir/phoenix 作为后端 API 的文件附件(序列化问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36654641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com