1、首先添加springMVC文件上传的jar
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 上传文件拦截,设置最大上传文件大小 10M=10*1024*1024(B)=10485760 bytes -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760" />
</bean>
3、Controller代码
/*
* 图片命名格式
*/
private static final String DEFAULT_SUB_FOLDER_FORMAT_AUTO = "yyyyMMddHHmmss";
/*
* 放置上传图片的文件夹!
*/
private static final String UPLOAD_PATH="/upload/img/";
@RequestMapping("/uploadImg")
public void uplodaImg(@RequestParam("upload")MultipartFile file,HttpServletRequest request, HttpServletResponse response, @RequestParam("CKEditorFuncNum")String CKEditorFuncNum)
throws IllegalStateException, IOException {
PrintWriter out =response.getWriter();
String fileName=file.getOriginalFilename();
String uploadContentType =file.getContentType();
String expandedName ="";
if (uploadContentType.equals("image/pjpeg")
|| uploadContentType.equals("image/jpeg")) {
// IE6上传jpg图片的headimageContentType是image/pjpeg,而IE9以及火狐上传的jpg图片是image/jpeg
expandedName = ".jpg";
} else if (uploadContentType.equals("image/png")
|| uploadContentType.equals("image/x-png")) {
// IE6上传的png图片的headimageContentType是"image/x-png"
expandedName = ".png";
} else if (uploadContentType.equals("image/gif")) {
expandedName = ".gif";
} else if (uploadContentType.equals("image/bmp")) {
expandedName = ".bmp";
} else {
out.println("<script type=\"text/javascript\">");
out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum
+ ",''," + "'文件格式不正确(必须为.jpg/.gif/.bmp/.png文件)');");
out.println("</script>");
return ;
}
if (file.getSize()> 600 * 1024) {
out.println("<script type=\"text/javascript\">");
out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum
+ ",''," + "'文件大小不得大于600k');");
out.println("</script>");
return ;
}
DateFormat df = new SimpleDateFormat(DEFAULT_SUB_FOLDER_FORMAT_AUTO);
fileName = df.format(new Date())+expandedName;
/** 构建上传图片的保存目录* */
String saveDir = UPLOAD_PATH+ fileName; //相当于("/upload/img/"+fileName)
/** 得到文件保存目录的真实路径* */
/**一定要注意这里,这里的路径就是上传图片所在的项目根路径,在编译后的文件夹里面,前端可以根据wepapp下的路径直接取即可。
*不确定的话,就打印出这句话,然后看看下面的配置的前端是怎么取到的
*/
String imgRealPathDir = request.getSession().getServletContext().getRealPath(saveDir);
File targetFile = new File(imgRealPathDir);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
file.transferTo(targetFile);//注意,项目经常会在这里出现错误,错误的原因一般都是配的上传路径或者前端获取的路径不对,一定要注意这里
// 返回"图像"选项卡并显示图片 request.getContextPath()为web项目名,只适合jsp页面使用,不适用于后台Java代码
out.println("<script type=\"text/javascript\">");
out.println("window.parent.CKEDITOR.tools.callFunction(" + CKEditorFuncNum
+ ",'" + request.getContextPath()+"/upload/img/" + fileName + "','')");
out.println("</script>");
return ;
}