springmvc webuploader 附件上传

页面


<link rel="stylesheet" type="text/css" href="${ctx}scripts/webuploader-0.1.5/webuploader.css">

<script type="text/javascript" src="${ctx}scripts/webuploader-0.1.5/webuploader.js">script>

<div id="uploader-demo">
<div id="filePicker">选择图片div>
div>
<div id="fileList" class="uploader-list">div>

java后台

//上传文件
		@RequestMapping(value = "/uploadFile")
		@ResponseBody
		public String uploadFile(@RequestParam("file") MultipartFile attach, HttpServletRequest request){
			String basepath ="E:/1111/"; //request.getSession().getServletContext().getRealPath("/");
			String functionPath = request.getParameter("functionPath");
			if(functionPath == null || "".equals(functionPath)) {
				functionPath = "other";
			}
			
			String name = attach.getOriginalFilename();
			String type = name.substring(name.lastIndexOf(".") + 1);
			if (!FileUploadUtil.checkFileName(type, FileUploadUtil.IMG_SUFFIX)) {
				return "error";
			}
			
			String replyPath = FileUploadUtil.uploadImg(attach, functionPath, basepath);
			return replyPath;
		}
/**
	 * 上传图片
	 * @param attach MultipartFile类型图片
	 * @param functionPath 功能路径
	 * @return error:出异常;图片保存后相对路径
	 */
	public static String uploadImg(MultipartFile attach,String functionPath,String basepath){
		
		String nowPath=FormatDate.toShortFormat(new Date());
		String path = basepath + "upload/img/"+ functionPath+"/"+nowPath  +"/";
		
		 File dicimg = new File(path);
	     if (!dicimg.exists()) {
	         dicimg.mkdirs();
	     }
		
		String name = attach.getOriginalFilename();
        String type = name.substring(name.lastIndexOf(".") + 1);
        

        String now=System.nanoTime()+"";
        String newName=now+"."+type;
        
        String filePath = path + newName;
		
		FileOutputStream write = null;
			try {
					write = new FileOutputStream(new File(filePath));
				  	write.write(attach.getBytes());
			        write.flush();			        
			        return "/upload/img/" + functionPath +"/"+ nowPath  +"/" + newName;
			} catch (Exception e) { 
				e.printStackTrace();
				return "error";
			} finally{
				try {
					if(write !=null){
						write.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
	}

你可能感兴趣的:(java)