MultipartFile
MultipartFile是spring类型,代表HTML中form data方式上传的文件,包含二进制数据+文件名称。 --来自百度知道
最近有个功能是接收前端界面上传的excel文件
public static final String SEPARATOR = System.getProperty("file.separator");
public static final String DIR_FILE = System.getProperty("user.dir") + SEPARATOR + "file" + SEPARATOR;
@PostMapping("/batch/charging")
public void batchCharging(@RequestParam("file") MultipartFile file,HttpServletResponse response) {
String fileName = file.getOriginalFilename();
logger.info("接收上传文件的filename:" + fileName);
String fileFullPath = DIR_FILE + fileName;//下载文件到本地项目路径
InputStream input = null;
FileOutputStream fos = null;
try {
String name = fileName.substring(fileName.lastIndexOf("."));
if(!".xls".equals(name) && !".xlsx".equals(name))
throw new Exception("请上传Excel格式的文件");
// 将接收到的Excel文件下载到文件目录中
input = file.getInputStream();
File f = new File(DIR_FILE);
if (!f.exists()) {
f.mkdirs();
}
fos = new FileOutputStream(fileFullPath);
int size = 0;
byte[] buffer = new byte[1024];
while ((size = input.read(buffer, 0, 1024)) != -1) {
fos.write(buffer, 0, size);
}
// 读取Excel文件内容
//........
// 响应信息 json字符串格式
Map<String, Object> responseMap = new HashMap<String, Object>();
responseMap.put("flag", true);
// 生成响应的json字符串
String jsonResponse = JSONObject.toJSONString(responseMap);
sendResponse(jsonResponse, response);
} catch (Exception e) {
// 响应信息 json字符串格式
Map<String, Object> responseMap = new HashMap<String, Object>();
responseMap.put("flag", false);
responseMap.put("errorMsg", e.getMessage());
String jsonResponse = JSONObject.toJSONString(responseMap);
sendResponse(jsonResponse, response);
} finally {
if (input != null) {
input.close();
}
if (fos != null) {
fos.close();
}
}
}
/**
* 返回响应
*
* @throws Exception
*/
private void sendResponse(String responseString, HttpServletResponse response) throws Exception {
response.setContentType("application/json;charset=UTF-8");
PrintWriter pw = null;
try {
pw = response.getWriter();
pw.write(responseString);
pw.flush();
} finally {
IOUtils.closeQuietly(pw);
}
}