1.在SpringMVC 配置文件applicationContext.xml中配置依赖,
文件上传依赖类:CommonsMultipartResolver
<bea id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设置默认编码 --> <property name="defaultEncoding" value="utf-8"></property> <!-- 上传图片最大大小1M--> <property name="maxUploadSize" value="2053799"></property> <!-- uploadTempDir为上传的临时目录 --> <property name="uploadTempDir" value="resource/temporary_file"></property>
</bean>
2.配置完成并不报错的情况下,在控制层应该是可以接受到上传的文件信息了。
后台以MultipartFile 类来接收前台的文件;之后读取文件,获取字符流。写人另一个文件对象中,这样便完成了文件上传。
@RequestMapping(value="/insertSnapShot.do",method=RequestMethod.POST)@ResponseBodypublic String insertSnapShot(@RequestParam("file") MultipartFile file,SnapShot snapshot,HttpServletRequest request){ JSONObject jsonText=new JSONObject(); if(snapshot!=null){ String serverFileUrl = request.getSession().getServletContext().getRealPath(""); String photoResourceRootFileUrl = "resource/snapShot";//照片根目录 snapshot.setUser_id(153); File photoFile;//文件 String fileuffix;//文件后缀 String fileName;//文件名称 StringBuffer photoUrls = new StringBuffer(); if(!file.isEmpty()){//当前文件长度大于0,表示有文件流存在 fileuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));//文件后缀 fileName = System.currentTimeMillis()+"_"+(snapshot.getUser_id());//命名规则:用户id_当前毫秒值_第几张.suffix。文件重命名 photoFile = new File(serverFileUrl+photoResourceRootFileUrl, fileName+fileuffix);//照片原图(存放于comment_photo) //判断原文件是否存在,不存在则新建 if(photoFile.exists()){//不存在返回true photoFile.mkdirs();//新建文件或文件夹 System.out.println("不存在!"); } try { file.transferTo(photoFile);//文件写入文件夹 System.out.println("写入文件夹!"); } catch (IllegalStateException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.err.println("照片文件流写入异常!!!"); } if(photoUrls.length() > 0){//";"照片间半角分号分隔 photoUrls.append(";"); } photoUrls.append(photoResourceRootFileUrl+fileName+fileuffix);//拼接原图路径地址 try { //再从原图文件夹读取文件流,压缩后写入缩略图 文件夹 Thumbnails.of(photoFile).size(200, 300).toFile(new File(serverFileUrl+photoResourceRootFileUrl, fileName+"_thumbnail"+fileuffix));//照片缩略图(存放于thumbnail_photo) } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.err.println("用户上传图片缩略图写入异常!"); } snapshot.setImgpath(photoUrls.toString()); int i=snapshotService.insertSnapShot(file, snapshot); if(i>0){ jsonText.put("type", "1");//信息新增成功 } } }else{ jsonText.put("type", "2");//信息新增失败 } return jsonText.toString(); }