1、首先必须配置bean
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485760"/> <property name="resolveLazily" value="true"/> <property name="maxInMemorySize" value="4096"/> <property name="defaultEncoding" value="UTF-8"/> </bean>
2、ftl页面代码
<form id="fileForm" method="post" enctype="multipart/form-data"> <input type="text" id="someText" name="someText"> <input type="file" name="file" id="file"> </form>
3、js代码
var someText= $("#someText").val(); var file = $("#file")[0].files[0]; //获取标签值好像函数与浏览器不兼容,网上的大多是通过$("#file").files[0]获取, 我这里必须通过$("#file")[0].files[0]才能获取到值 var formData = new FormData(); formData.append('someText', someText); formData.append('file', file); $.ajax({ type:"post", url:'请求路径', data:formData, dataType:'json', cache:false, contentType: false, processData: false, success: function(data) { // 结果处理 } });
4、后台代码
@RequestMapping(value = "路径", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public Object uploadFile(@RequestParam(value = "someText", required = false) String someText,
@RequestParam(value = "file", required = false) MultipartFile file,
HttpServletRequest request) {//required = false才能获取到值
XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());
for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
XSSFSheet sheetAt = workbook.getSheetAt(numSheet);
if (sheetAt == null) {
continue;
}
// 循环行Row
for (int rowNum = 0; rowNum <= sheetAt.getLastRowNum(); rowNum++) {
XSSFRow row = sheetAt.getRow(rowNum);
if (row == null) {
continue;
}
// 循环列Cell
for (int cellNum = 0; cellNum <= row.getLastCellNum(); cellNum++) {
//在此可进行获取单元格值并入库
getValue(row,cellNum);
}
}
}
}
//单元格类型转换并获取值
private String getValue(XSSFRow row, int cellNum) {
XSSFCell cell = row.getCell(cellNum);
if (cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
return String.valueOf((int) cell.getNumericCellValue());
} else {
return String.valueOf(cell.getStringCellValue()).equals("") ? "" : String
.valueOf(cell.getStringCellValue());
}
}