1.文件上传客户端三要素
- 表单项type=“file”
- 表单的提交方式是post
- 表单的enctype属性是多部分表单形式,及enctype=“multipart/form-data”
<form action="${pageContext.request.contextPath}/quick22" method="post" enctype="multipart/form-data">
名称:<input type="text" name="username"><br/>
年龄:<input type="text" name="age"><br/>
文件:<input type="file" name="upload"><br/>
<input type="submit" value="提交">
</form>
2.文件上传原理
- 当form表单修改为多部分表单时,request.getParameter()将失效
- enctype="application/x-www-form-urlencoded"时,form表单的正文内容格式是key=vakue&key=vakue&key=vakue
- enctype="multipart/form-data"时,请求正文内容就变成多部分形式
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/27f7e144855ae1d2ebf6d04f805dbc7b.png)
3.单文件上传步骤
①引入fileupload和io依赖
//引入fileupload和io依赖
implementation 'commons-fileupload:commons-fileupload:1.4'
implementation 'commons-io:commons-io:2.11.0'
②在Spring-MVC中配置文件上传解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5242800"/>
<property name="maxUploadSizePerFile" value="5242800"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
③编写文件上传代码
@ResponseBody
@RequestMapping("/quick22")
fun save22(username: String?, upload:MultipartFile):String? {
println(username)
println(upload)
val filename = upload.originalFilename
upload.transferTo(File("E:\\img\\$filename"))
return username
}
④测试
<form action="${pageContext.request.contextPath}/quick22" method="post" enctype="multipart/form-data">
名称:<input type="text" name="username"><br/>
文件:<input type="file" name="upload"><br/>
<input type="submit" value="提交">
</form>
4.多文件上传
①多名称接收
@ResponseBody
@RequestMapping("/quick22")
fun save22(username: String?, upload:MultipartFile, upload2:MultipartFile):String? {
println(username)
println(upload)
val filename = upload.originalFilename
upload.transferTo(File("E:\\img\\$filename"))
upload2.transferTo(File("E:\\img\\${upload2.originalFilename}"))
return username
}
②数组接收
<form action="${pageContext.request.contextPath}/quick23" method="post" enctype="multipart/form-data">
文件1:<input type="file" name="files"><br/>
文件2:<input type="file" name="files"><br/>
文件3:<input type="file" name="files"><br/>
<input type="submit" value="提交">
</form>
@ResponseBody
@RequestMapping("/quick23")
fun save23(files:Array<MultipartFile>?):MultipartFile? {
if (!files.isNullOrEmpty()){
for (file in files){
val filename = file.originalFilename
println(filename)
file.transferTo(File("E:\\img\\$filename"))
}
}
return null
}