@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public Json upload(@RequestParam(value = "imageFile") MultipartFile file,
HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String temppath = "/file";
Json j = new Json();
// 构建文件名称multipartFile
String oldName = file.getOriginalFilename();
if (!oldName.endsWith("jpg") && !oldName.endsWith("png")) {
// 判断是否是图片文件
j.setMsg("上传文件应该是jpg或png格式");
j.setSuccess(false);
return j;
}
// 获取文件的后缀
String suffix = oldName.substring(oldName.indexOf('.'));
String name = String.valueOf(System.currentTimeMillis()).concat(suffix);
String path = req.getSession().getServletContext()
.getRealPath(temppath);
try {
File filepath = new File(path);
if (!filepath.exists()) {
filepath.mkdir(); // 创建目录
}
OutputStream os = new FileOutputStream(filepath.getPath() + "/"
+ name);
InputStream is = file.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.flush();
os.close();
is.close();
j.setSuccess(true);
j.setMsg("上传成功");
} catch (Exception e) {
j.setMsg("上传失败");
j.setSuccess(false);
e.printStackTrace();
}
j.setErrorinfo(req.getContextPath() + temppath + "/" + name);
j.setObject(path + "\" + name);
return j;
}
上传后的文件:
