文件上传:
(通过userType判断需要下载的文件,可忽略)
@RequestMapping(value = "/v1/user/template/download/{userType}", method = RequestMethod.GET)
public Object downloadBatchRegistUserTemplateFile(@PathVariable Integer userType, HttpServletResponse resp){
logger.info("OrganUserController.downloadBatchRegistUserTemplateFile>>>>>>userType:" + userType );
if (userType == null ) {
return "参数为空";
}
// path是指下载的模板文件的路径
String path = "D:/RATemplate";
// name 模板文件名
String name = null;
if(userType == Constants.USER_TYPE_PERSON_1){
name = "个人用户.xlsx";
}
if(userType == Constants.USER_TYPE_ORGAN_2){
name = "机构用户.xlsx";
}
if(userType == Constants.USER_TYPE_DEVICE_3){
name = "设备用户.xlsx";
}
String filename = path + "/" + name;
System.out.println(filename);
try {
resp.setHeader("Content-Disposition","attachment;fileName="+ URLEncoder.encode(name,"utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
ServletOutputStream out = resp.getOutputStream();
FileInputStream fis = new FileInputStream(filename);
int len;
byte[] b = new byte[1024];
while((len=fis.read(b))!= -1){
out.write(b, 0 ,len);
}
fis.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Result result = new Result();
logger.info("OrganUserController.downloadBatchRegistUserTemplateFile>>>>>>result:" + JsonUtils.object2Json(result));
return result.getInfo();
}
文件上传:
@RequestMapping(value = "/v1/user/organ/regist/template", method = RequestMethod.POST)
public Object batchRegistOrganUserByTemplateFile(@RequestParam("file") MultipartFile file, HttpServletResponse resp) {
logger.info("OrganUserController.batchRegistOrganUserByTemplateFile>>>>>>file:" + file);
if (file.isEmpty()) {
return "上传失败,请重新选择文件";
}
Result result = new Result();
//获取文件名
String fileName = file.getOriginalFilename();
//保存路径
String filePath = "D:/UserRegistFile";
File dest = new File(filePath + "/"+ fileName);
try {
file.transferTo(dest);
logger.info("上传成功");
} catch (IOException e) {
logger.error(e.toString(), e);
return "上传失败!";
}
logger.info("OrganUserController.batchRegistOrganUserByTemplateFile>>>>>>result:" + JsonUtils.object2Json(result));
return result.getInfo();
}