提问者:小点点

了解enctype=Multipart/form-data在Spring mvc中的工作


在我读过的《Spring in Action》一书中,post提交的默认内容类型是application/x-www-form-urlencoded,采用由&符号分隔的名称-值对的形式。(我相信这些都作为HTTP POST请求的主体负载。)

我进一步了解到,当enctype设置为multipart/form数据时,每个字段将作为POST请求的不同部分提交,而不仅仅是作为另一个名称-值对提交。

第一季度

服务器端代码

@RequestMapping(method=RequestMethod.POST)
public String addSpitterFromForm(@Valid Spitter spitter,
    BindingResult bindingResult,
    @RequestParam(value="image", required=false)
Accept file upload
      MultipartFile image) {
if(bindingResult.hasErrors()) {
  return "spitters/edit";
}
spitterService.saveSpitter(spitter);
try {
  if(!image.isEmpty()) {
    validateImage(image);
Validate image
      saveImage(spitter.getId() + ".jpg", image); //
    }
  } catch (ImageUploadException e) {
    bindingResult.reject(e.getMessage());
    return "spitters/edit";
}
  return "redirect:/spitters/" + spitter.getUsername();
}

客户端代码

    <sf:form method="POST"
                     modelAttribute="spitter"
                     enctype="multipart/form-data">
//other stuff
     <tr>
         <th><sf:label path="fullName">Full name:</sf:label></th>
         <td><sf:input path="fullName" size="15" /><br/>
             <sf:errors path="fullName" cssClass="error" />
         </td>
     </tr><tr>
      <th><label for="image">Profile image:</label></th>
      <td><input name="image" type="file"/>
    </tr>
//other stuff
    </sf:form>

从代码中,我倾向于认为只有输入type="file "以一种新的方式发送。其余的都以键值对的形式发送。我想这本书也说了同样的话“当表单被提交时,它将作为一个多部分表单发布,其中一部分包含图像文件的二进制数据。”

第 2 季度


共1个答案

匿名用户

首先,多部分/形式数据的enctype不是Spring-MVC的东西,它是< code >的一个属性

--AaB03x
content-disposition: form-data; name="field1"
content-type: text/plain;charset=windows-1250
content-transfer-encoding: quoted-printable
Joe owes =80100.
--AaB03x

请注意,Joe 欠 =80100。 表示 Joe 欠 100 欧元

您可以在HTML4规范中找到另一个示例,其中显示了上传两个或更多文件时的更具体示例(我的评论发布在之后

Content-Type: multipart/form-data; boundary=AaB03x <-- mark for the whole request

--AaB03x <-- content of a part
Content-Disposition: form-data; name="submit-name" <-- field name

Larry <-- content of the field
--AaB03x <-- content of a part
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=BbC04y

--BbC04y <-- content of a part containing a file
Content-Disposition: file; filename="file1.txt"
Content-Type: text/plain

... contents of file1.txt ...
--BbC04y <-- content of a part containing a file
Content-Disposition: file; filename="file2.gif"
Content-Type: image/gif
Content-Transfer-Encoding: binary

...contents of file2.gif...
--BbC04y-- <-- end of parts containing file
--AaB03x-- <-- end of whole request data