formdata 实现文件上传
页面:
<div class="col-sm-12 search-collapse" >
<div class="select-list">
<ul>
<li>
<input name="file" type="file" id="uploadFile" required title="提示:仅允许导入“xls”或“xlsx”格式文件! 第一列是名字,第二列是角色">
</li>
<li>
<input name="tableName" id="tableName" required type="text" placeholder="请输入全字母或者字母加数字">
</li>
<li>
<select name="caseName" id="caseName" required>
</select>
</li>
<li>
<a class="btn btn-info" onclick="executeUpload()" >
<i class="fa fa-upload"></i> 执行
</a>
</li>
</ul>
</div>
</div>
js:
function executeUpload() {
var fd = new FormData();
fd.append("file",$("#uploadFile")[0].files[0]);
fd.append("tableName",$("#tableName").val());
fd.append("caseName",$("#caseName").val());
$.ajax({
url: prefix+"/uploadFile",
method: "POST",
data: fd,
contentType: false,
processData: false,
cache: false,
success: function(data){
alert(JSON.stringify(data))
}
})
}
controller:
public AjaxResult uploadFile(HttpServletRequest request) throws IOException {
String tableName = request.getParameter("tableName");
String caseName = request.getParameter("caseName");
//todo 判断表是否存在
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multiRequest.getFile("file");
String originalFilename = file.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
}