JS代码:


	 //初始化上传图片框
	initImgFilebox:function(DOM){
	    uploadify({  
            'DOM':DOM,
	    	'buttonText' : '浏览',  //上传按钮显示内容,还有个属性可以设置按钮的背景图片
            'height' : 30,  
            'swf' : '/bfs/lib/scripts/uploadify/3.2/uploadify.swf',  // 控件flash文件位置  
            'uploader' : '/bfs/bfs/fileup/uploadfile?pathState=1',   // 后台处理的请求地址,后面追加了jsessionid,用来标示使用当前session(默认是打开新的session,会导致存在session校验的请求中产生302错误)
            'width' : 80,  
            'fileSizeLimit' : '1000KB',  
            'multi' : true,  // true 选择多文件上传
            'auto':true,  // true自动上传
            'fileObjName'   : 'file',  //文件对象名称,用于后台获取文件对象时使用,详见下面的java代码  
            'fileTypeExts' : '*.jpg;*.png;', //控制可上传文件的扩展名,启用本项时需同时声明fileDesc   
            'onFallback' : function() {//检测FLASH失败调用  
                alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。");  
            },  
            'onUploadSuccess' : function(file, data, response) {
            	
                var data = jQuery.parseJSON(data);
                if(data.success==="true"){
                    setAirStationPoint.showImg(data);
               
                }
            }  
        });  
	    
	}


后端代码:


	@ResponseBody
	@RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
	public void uploadFile() throws Exception {
		Map<String,Object> map = new HashMap<String,Object>();
		String path = "";
		PrintWriter writer = null;
		String orgfilename = "";
		// 判断路径状态
		String pathState = request.getParameter("pathState");
		try {
			Properties pro = new Properties();
			pro.load(FileUpController.class.getResourceAsStream("/file.properties"));
			DiskFileItemFactory factory = new DiskFileItemFactory();
			String filepath = pro.getProperty("path");
			if (pathState!=null&&"1".equals(pathState)) {
				path = request.getSession().getServletContext().getRealPath("/")+ filepath;
			} else {
				path = filepath;
			}
			// path = request.getSession().getServletContext().getRealPath("/")
			// + filepath;
			factory.setRepository(new File(path));
			factory.setSizeThreshold(1024 * 1024);
			ServletFileUpload upload = new ServletFileUpload(factory);
			// try {
			// 可以上传多个文件
			List<FileItem> list = upload.parseRequest(request);
			for (FileItem item : list) {
				if (!item.isFormField()) {
					orgfilename = item.getName();
					String extname = orgfilename.substring(orgfilename.lastIndexOf(".") + 1, orgfilename.length());
					String fileName = UUID.randomUUID().toString().replaceAll("-", "");
					System.out.println(fileName);
					String serverfilename = fileName + "." + extname;
					File headPath = new File(path);// 获取文件夹路径
					if (!headPath.exists()) {// 判断文件夹是否创建,没有创建则创建新文件夹
						headPath.mkdirs();
					}
					OutputStream out = new FileOutputStream(new File(path, serverfilename));
					InputStream in = item.getInputStream();
					int filesize = in.available();
					int length = 0;
					byte[] buf = new byte[1024];
					while ((length = in.read(buf)) != -1) {
						out.write(buf, 0, length);
					}
					in.close();
					out.close();
					/** 将上传处理后的数据返回 **/
					map.put("orgfilename", orgfilename);
					map.put("filepath", (filepath + "\\" + serverfilename));

					FileInfoVO fiv = new FileInfoVO();
					fiv.setOrgfilename(orgfilename);
					fiv.setServerfilename(serverfilename);
					fiv.setFilepath(filepath + "\\" + serverfilename);
					fiv.setFilesize(new Double(filesize));
					fiv.setExtname(extname);
					fiv.setCtime(new Date());
					fileInfoService.insertSelective(fiv);
					map.put("fileid", fiv.getFileid());
					map.put("success", "true");
					// HttpRequestUtil.sendPost(strURL, param);
					break;
				}
			}

			response.setContentType("text/xml; charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");
			response.setHeader("Pragma", "no-cache");
			writer = this.response.getWriter();
			String msg = JSON.toJSONString(map);
			writer.print(msg);

		} catch (Exception e) {
			logger.error("上传文件出错:" + e);
			map.put("success", "false");
			map.put("orgfilename", orgfilename);
			map.put("filepath", path);
			map.put("error", e.getMessage());
			String msg = JSON.toJSONString(map);
			if (writer == null) {
				writer = this.response.getWriter();
			}
			writer.print(msg);
		} finally {
			if (writer != null) {
				writer.close();
			}
		}
	}



代码链接:

欢迎留言