@FormDataParam 和@FormParam 有什么区别

What is difference between @FormDataParam and @FormParam

@FormDataParam@FormParam有什么区别?

我在一个方法中使用了多个 @FormDataParam,但它引发了媒体类型不受支持的错误。但是当我使用 @FormParam 时,我得到了值。

所以,我想知道这两者有什么区别?

  • @FormDataParam 应该与多部分类型数据(即 multipart/form-dataMediaType.MULTIPART_FORM_DATA)一起使用,其原始形式看起来像

      Content-Type: multipart/form-data; boundary=AaB03x
    
      --AaB03x
      Content-Disposition: form-data; name="submit-name"
    
      Larry
      --AaB03x
      Content-Disposition: form-data; name="files"; filename="file1.txt"
      Content-Type: text/plain
    
      ... contents of file1.txt ...
      --AaB03x--
    

    Multipart 主要用于发送二进制数据,如非文本文件,或随文件一起发送任意数据、元数据或相关数据。

  • @FormParam 用于 url 编码的请求参数(即 application/x-www-form-urlencodedMediaType.APPLICATION_FORM_URLENCODED),原始形式看起来像

      param1=value1&param2=value2
    

这两种类型主要用于客户端表单。例如

<form method="POST" action="someUrl">
    <input name="gender" type="text">
    <input name="name" type="text">
</form>

以上将发送请求参数为application/x-www-form-urlencoded。它将以原始形式发送为

gender=male&name=peeskillet

在服务器端,我们可以为表单中的每个命名参数使用一个@FormParam

@FormParam("gender") String gender, @FormParam("name") String name

但是如果我们需要将图片与参数一起发送,application/x-form-url-encoded 数据类型是不够的,因为它只处理文本。所以我们需要使用Multipart

<form method="POST" action="someUrl", enctype="multipart/form-data">
    <input name="gender" type="text">
    <input name="name" type="text">
    <input name="avatar" type="file">
</form>

这里指定了 Multipart 类型,现在浏览器将发送类似

的请求
Content-Type: multipart/form-data; boundary=AaB03x

--AaB03x
Content-Disposition: form-data; name="gender"

Male
--AaB03x
Content-Disposition: form-data; name="name"

Peskillet
--AaB03x
Content-Disposition: form-data; name="avatar"; filename="image.png"
Content-Type: image/png

... binary content of image file ...
--AaB03x--

在服务端,和上面的application/x-www-form-urlencoded例子类似,对于每个Multipart参数(或者更准确的说是字段),我们可以用@FormDataParam来表示每个参数

@FormDataParam("gender") String gender,
@FormDataParam("name") String name,
@FormDataParam("avatar") InputStream avatar

另请参阅:

来自文档 FormParam:

Binds the value(s) of a form parameter contained within a request entity body to a resource method parameter. Values are URL decoded unless this is disabled using the Encoded annotation. A default value can be specified using the DefaultValue annotation. If the request entity body is absent or is an unsupported media type, the default value is used.

FormDataParam

Binds the named body part(s) of a "multipart/form-data" request entity body to a resource method parameter.