前台jsp
<form action="${pageContext.request.contextPath}/file/upload" method="post" >
<input type="file" name="file"/>
<button type="submit">上传</button>
</form>
后台接受不到 上传文件要特殊定义
加上enctype="multipart/form-data"就好使了
<form action="${pageContext.request.contextPath}/file/upload" method="post"enctype="multipart/form-data" >
<input type="file" name="file"/>
<button type="submit">上传</button>
</form>
后台代码
/***
* 保存图片文件
* @param file
* @return
*/
private String saveFile(HttpServletRequest request, MultipartFile file,
String fileName) {
SimpleDateFormat df = new SimpleDateFormat("yyyyMM");
SimpleDateFormat sdf = new SimpleDateFormat("dd");
String filePath = "";
String Path = "";
//判断文件是否为空
if (!file.isEmpty()) {
try {
filePath = getPath(request)
+ "/upload/"+ df.format(new Date())+ "/"
+ sdf.format(new Date()) + "/" + fileName;
Path = "/upload/"+ df.format(new Date())+ "/"+ sdf.format(new Date()) + "/" + fileName;
System.err.println(filePath);
File saveDir = new File(filePath);
if (!saveDir.getParentFile().exists())
saveDir.getParentFile().mkdirs();
// 转存文件
file.transferTo(saveDir);
// 压缩大小
Thumbnails.of(saveDir).size(800, 600).toFile(saveDir);
return Path;
} catch (Exception e) {
e.printStackTrace();
}
}
return Path;
}
@ResponseBody
@RequestMapping("/upload")
public Json filesUpload(@RequestParam("file") MultipartFile file,Photos photos,
HttpServletRequest request) {
Json json = new Json();
// 保存文件
/*5017155
* String fileName = System.currentTimeMillis() +
* file.getOriginalFilename().substring(
* file.getOriginalFilename().lastIndexOf("."));
*/
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
String fileName = df.format(new Date())
+ file.getOriginalFilename().substring(
file.getOriginalFilename().lastIndexOf("."));
String filePath = saveFile(request, file, fileName);
String realpath = getPath(request);
String path = realpath+"/" + filePath;
if(photos.getPhotoone()!=null&&!"".equals(photos.getPhotoone())){
File fil = new File(realpath+photos.getPhotoone());
if(fil.exists()){
fil.delete();
}
}
if (filePath != null || !filePath.equals("")) {
json.setSuccess(true);
json.setMsg(filePath);
json.setImg(path);
} else {
json.setSuccess(false);
json.setMsg("上传失败");
}
return json;
}