@ResponseBody
@RequestMapping("/upload")
public String upload(HttpServletRequest request, @RequestParam(value = "uploadfile") MultipartFile file,
@RequestParam(value = "policyno", required = false)String policyno) {
AjaxResult Result = new AjaxResult();
Result.setStatus(HttpStatus.SC_OK);
FileUpload fileUpload = new FileUpload();
fileUpload.setPolicyno(policyno);
int count = fileUploadService.queryCount(fileUpload);
if (count >= 5) {
Result.setStatusText("上传文件过多:只能上传5个的文件");
return JSON.toJSONString(Result);
}
InputStream is = null;
String name = file.getOriginalFilename();
if (!file.isEmpty() && file.getSize() > 0) {
System.out.println("文件长度: " + file.getSize());
System.out.println("文件类型: " + file.getContentType());
System.out.println("文件名称: " + file.getName());
System.out.println("文件原名: " + name);
System.out.println("========================================");
if (file.getSize() > 1024 * 1024 * 2) {
Result.setStatus(HttpStatus.SC_OK);
Result.setStatusText("上传失败:只能上传小于 2 M 的文件");
Result.setData(name);
return JSON.toJSONString(Result);
}
try {
is = file.getInputStream();
byte[] fileByte = toByteArray(is);
FileUpload fileU = new FileUpload();
fileU.setAttachment(fileByte);//该字段对应的数据库类型为mediumblob,最大4M
fileU.setFilename(name);
fileU.setInsertdate(new Date());
fileU.setUpdatedate(new Date());
fileU.setDeleted("false");
fileU.setType("claim");
fileU.setContentType(file.getContentType());
fileU.setPolicyno(policyno);
fileU.setId(UUID.randomUUID().toString());
boolean flag = fileUploadService.insertFile(fileU);
if (flag) {
Result.setStatusText("上传成功");
}else {
Result.setStatusText("上传失败");
}
Result.setData(name);
} catch (FileNotFoundException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getMessage(), e);
} finally {
try {
// 关闭输入流
if (null != is) {
is.close();
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
} else {
Result.setStatusText("未选择文件");
}
return JSON.toJSONString(Result);
}
private static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
copy(input, output);
return output.toByteArray();
}
private static int copy(InputStream input, OutputStream output) throws IOException {
long count = copyLarge(input, output);
if (count > 2147483647L) {
return -1;
}
return (int) count;
}
private static long copyLarge(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[4096];
long count = 0L;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}