前端同时传入多个文件和文本
目录
前端同时传入多个文件和文本
前端传入多个文件和文本
我现在在做发送邮件的前端界面,所以需要实现上传自定义个数的附件和文本的功能。写一篇博文记录遇到的问题。
1、前端传参
<form id="writeMailForm" style="margin-top: 15px" enctype="multipart/form-data" method="post">
<table width="100%">
<tbody>
<tr>
<td class="col-sm-2">
<span class="glyphicon glyphicon-user"></span> 收件人:
</td>
<td class="col-sm-10">
<input id="recipient" name="recipient" type="text" style="width: 100%;margin-left: 0px"/>
</td>
</tr>
</tbody>
</table>
<table style="margin-top: 15px;width: 100%">
<tbody>
<tr>
<td class="col-sm-2">
<span class="glyphicon glyphicon-asterisk"></span> 主题:
</td>
<td class="col-sm-10">
<input id="subject" name="subject" type="text" style="width: 100%;margin-left: 0px"/>
</td>
</tr>
</tbody>
</table>
<table style="margin-top: 15px;width: 100%">
<tbody>
<tr>
<td>
<span style="margin-left: 120px" class="glyphicon glyphicon-folder-open"/>
</td>
<td>
<input id="files" name="files" style="margin-left: -25px;width: 390px" type="file" multiple="multiple" value="上传文件">
</td>
</tr>
</tbody>
</table>
<table style="margin-top: 15px;width: 100%;height: 150px">
<tbody>
<tr>
<td class="col-sm-2">
<div style="margin-top: -73px">
<span class="glyphicon glyphicon-pencil"></span> 正文:
</div>
</td>
<td class="col-sm-10">
<textarea id="text" name="text" style="width: 100%;height: 100%"> </textarea>
</td>
</tr>
</tbody>
</table>
<div align="left" style="float:left">
<input type="button" id="sendMailBtn" class="btn btn-success btn-block"
style="width: 500px;margin-left: 123px;margin-top: 15px" onclick="sendMail()" value="发送邮件">
</div>
</form>
需要注意的地方:
- form要设置enctype=“multipart/form-data” method=“post”,这种多部份数据编码类型,传参方式要用post
- 传file的input,要设置属性:multiple=“multiple”,这样就可以一下传多个文件
ajax部分:
sendMail = function () {
if($("#recipient").val().trim()==""||$("#subject").val().trim()==""){
alert("请填写完整的收件人和主题信息");
}else{
var formData = new FormData($("#writeMailForm")[0]);
alert(formData.get("recipient")+formData.get("subject")+formData.get("text"));
$.ajax({
url:"${pageContext.request.contextPath}/user/writeMail",
type:"POST",
encType: 'multipart/form-data',
data:formData,
processData: false,//jq不处理发出的数据
contentType: false,//不设置Content-Type请求头
success: function (res) {
alert(res.msg);
}
});
}
}
2、后端接收参数
- 处理多part的参数,需要再spring-mvc配置文件中设置multipartResolver:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="20971520"/> <!--总文件上传的大小限制-->
<property name="defaultEncoding" value="utf-8"></property>
</bean>
同时CommonsMultipartResolver类还需要引入maven依赖:
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
Controller层接收参数还是正常接收,form里面每一个参数,controller方法就设置一个对应的参数,注意文件参数:
@RequestParam(value = “files”) MultipartFile[] files