multipart/form-data 和 FormType 验证 [英] multipart/form-data and FormType validation

本文介绍了multipart/form-data 和 FormType 验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!


我正在使用 FOSRestBundle 构建 API,并且处于需要实施处理包含二进制数据的新实体的创建.

I am building an API using the FOSRestBundle and am at the stage where I need to implement the handling of the creation of new entities that contain binary data.

遵循 随 REST API 请求发送二进制数据 将数据作为 multipart/form-data 发送对于我们的实现来说是最实用的,因为 Base64 需要增加约 33% 的带宽.

Following the methods outlined on Sending binary data along with a REST API request sending the data as multipart/form-data feels the most practical for our implementation due to the ~33% added bandwidth required for Base64.


当以 multipart/form-data 形式发送数据时,如何配置 REST 端点以处理请求中的文件并在 JSON 编码的实体上执行验证?

How can I configure the REST end point to both handle the file within the request and perform validation on the JSON encoded entity when sending the data as multipart/form-data?

在发送原始 JSON 时,我一直在使用 Symfony 的表单 handleRequest 方法对自定义 FormType 执行验证.例如:

When just sending the raw JSON I have been using Symfony's form handleRequest method to perform validation against the custom FormType. For example:

$form = $this->createForm(new CommentType(), $comment, ['method' => 'POST']);

if ($form->isValid()) {

  // Is valid


我喜欢这种方法的原因是,我可以根据操作是更新 (PUT) 还是新建 (POST) 来更好地控制实体的数量.

The reason I like this approach is so that I can have more control over the population of the entity depending whether the action is an update (PUT) or new (POST).

我知道 Symfony 的 Request 对象处理请求,因此以前 JSON 数据将是 content 变量,但现在在 request->parameters 下键入->[form key] 和文件包内的文件(request->files).

I understand that Symfony's Request object handles the request such that previously the JSON data would be the content variable but is now keyed under request->parameters->[form key] and the files within the file bag (request->files).



After giving up and looking at an alternative option of having a separate endpoint for the image upload. For example:

  1. 创建新评论.


  1. 上传图片到终点


我发现已经有一个包提供了各种 RESTful 上传过程.其中之一是我最初希望能够在提取文件的同时将 multipart/form-data 解析为实体.

I found there is already a bundle which provides various RESTful uploading processes. One of which was the one I originally wanted of being able to parse multipart/form-data into an entity whilst extracting the file.

这篇关于multipart/form-data 和 FormType 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

登录 关闭
发送“验证码”获取 | 15天全站免登陆