SpringMVC接收文件流上传和表单参数

在SpringMVC中,接收文件流非常简单,我们可以写个接口用来接收一些文件,同时还可以接收表单参数。
代码参考如下:

JAVA服务端代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 接收文件流
*
* @param request 请求
* @return OK
*/
@RequestMapping(value = "/receive/file", method = POST)
public String receiveFile(HttpServletRequest request) {
// 转换为 MultipartHttpServletRequest
if (request instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
// 通过表单中的参数名来接收文件流(可用 file.getInputStream() 来接收输入流)
MultipartFile file = multipartRequest.getFile("file");
System.out.println("上传的文件名称:" + file.getOriginalFilename());
System.out.println("上传的文件大小:" + file.getSize());
// 接收其他表单参数
String name = multipartRequest.getParameter("name");
String content = multipartRequest.getParameter("content");
System.out.println("name:" + name);
System.out.println("content:" + content);
return "OK";
} else {
return "不是 MultipartHttpServletRequest";
}
}

HTML页面代码

1
2
3
4
5
6
<form action="http://127.0.0.1:8080/receive/file" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<input type="text" name="content" value="内容">
<input type="text" name="name" value="名称">
<button type="submit">提交请求</button>
</form>