前提是项目已经搭建好SSM框架,因为只是简单地记录知识点,所以内容没有特别详细
1、在pom.xml文件中添加文件上传的Jar包:
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> <classifier>sources</classifier> </dependency>
2、SpringMVC的配置文件中添加 文件上传解析器
<!-- 定义文件上传解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设定默认编码 --> <property name="defaultEncoding" value="UTF-8"></property> <!-- 设定文件上传的最大值10MB,10*1024*1024 --> <property name="maxUploadSize" value="10485760"></property> </bean> 3、前台代码 upload.jsp中添加文件上传按钮 <form action="/user/toUpload" enctype="multipart/form-data" > <input type="file" name="uploadFile"> <input type="submit" value="提交"> </form> 4、后台代码Controller中添加后台处理 @RequestMapping("/pic/upload") @ResponseBody public PicUploadResult fileUpload(MultipartFile uploadFile){ /** * 文件上传的步骤 * 1、采用文件正确的接收方式接收(修改3处:配置文件/接口类型) * 2、判断是否是一个图片:0表示无异常,1表示异常(jpg|png|gif) * 3、判断是不是一个“正经”的图片:判断是否有width和height * 4、编辑磁盘目录D:jt_image/images/yyyy/MM/dd/HH/mm * 5、编辑相对路径url:http://image.jt.com/images/yyyy/MM/dd/HH/mm * 6、将文件保存 */ PicUploadResult picUpload = new PicUploadResult(); //1、获取文件名称 String fileName = uploadFile.getOriginalFilename(); //2、获取后缀名称 String endName = fileName.substring(fileName.lastIndexOf(".")); //3、判断是否为图片格式 if(!endName.matches("^.*(jpg|png|gif)$")){ picUpload.setError(1); logger.error("图片格式有误"); return picUpload; } //4、判断文件是否为一个正确的图片 try { //将文件转换为图片流的格式 BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream()); //获取宽度和高度,如果获取时有问题,则报异常! int width = bufferedImage.getWidth(); int height = bufferedImage.getHeight(); picUpload.setWidth(width+""); picUpload.setHeight(height+""); String localPath = "D:/jt_image/images/"; String datePath = new SimpleDateFormat("yyyy/MM/dd/HH/mm").format(new Date()); localPath += datePath+"/"+fileName; String urlPath = "http://image.jt.com/images/"; urlPath += datePath+"/"+fileName; File file = new File(localPath); //判断文件夹是否存在 if(!file.exists()){ //创建多个文件夹 file.mkdirs(); } //将文件写入 uploadFile.transferTo(file); picUpload.setUrl(urlPath); logger.info("~~~~~~~~~文件写入成功!" + localPath); return picUpload; } catch (IOException e) { e.printStackTrace(); logger.error("~~~~~~~~该文件非法!"); picUpload.setError(1); return picUpload; } } 5、PicUploadResult类返回json格式: public class PicUploadResult { private Integer error=0; //图片上传错误不能抛出,抛出就无法进行jsp页面回调,所以设置这个标识,0表示无异常,1代表异常 private String url; //应该是浏览器能够正常解析的具体页面路径 private String width; private String height; public Integer getError() { return error; } public void setError(Integer error) { this.error = error; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getWidth() { return width; } public void setWidth(String width) { this.width = width; } public String getHeight() { return height; } public void setHeight(String height) { this.height = height; } }