日期:2014-05-16  浏览次数:20712 次

SpringMVC + ajaxfileupload的多文件上传

    最近做一个springmvc ajax多文件上传,倒腾了下,查阅了部分资料搞定了!现在分享:

   1.Spring mvc

       a.xml配置:

    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
        <!-- set the max upload size1MB   1048576     -->
        <property name="maxUploadSize">
            <value>52428800</value>
        </property>
        <property name="maxInMemorySize">
            <value>2048</value>
        </property>
    </bean>
      b. 服务器端接收解析
        public void imgUpload(
		MultipartHttpServletRequest multipartRequest,
		HttpServletResponse response) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		Map<String, Object> result = new HashMap<String, Object>();
                //获取多个file
		for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {
			String key = (String) it.next();
			MultipartFile imgFile = multipartRequest.getFile(key);
			if (imgFile.getOriginalFilename().length() > 0) {
				String fileName = imgFile.getOriginalFilename();
                                //改成自己的对象哦!
				Object obj = new Object();
				//Constant.UPLOAD_GOODIMG_URL 是一个配置文件路径
				try {
					String uploadFileUrl = multipartRequest.getSession().getServletContext().getRealPath(Constant.UPLOAD_GOODIMG_URL);
					File _apkFile = saveFileFromInputStream(imgFile.getInputStream(), uploadFileUrl, fileName);
					if (_apkFile.exists()) {
						FileInputStream fis = new FileInputStream(_apkFile);
					} else
						throw new FileNotFoundException("apk write failed:" + fileName);
					List list = new ArrayList();
					//将obj文件对象添加到list
					list.add(obj);
					result.put("success", true);
				} catch (Exception e) {
					result.put("success", false);
					e.printStackTrace();
				}
			}
		}
		String json = new Gson().toJson(result,
				new TypeToken<Map<String, Object>>() {
				}.getType());
		response.getWriter().print(json);
	}

        //保存文件
	private File saveFileFromInputStream(InputStream stream, String path,
			String filename) throws IOException {
		File file = new File(path + "/" + filename);
		FileOutputStream fs = new FileOutputStream(file);
		byte[] buffer = new byte[1024 * 1024];
		int bytesum = 0;
		int byteread = 0;
		while ((byteread = stream.read(buffer)) != -1) {
			bytesum += byteread;
			fs.write(buffer, 0, byteread);
			fs.flush();
		}
		fs.close();
		stream.close();
		return file;
	}

2.关于前端代码

a.修改ajaxfileupload.js

  先到官网下载该插件.

  将源文件的createUploadForm的代码替换如下:

createUploadForm: function(id, fileElementId, data)
		{
			//create form	
	    	var formId = 'jUploadForm' + id;
	    	var fileId = 'jUploadFile' + id;
	    	var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');	
	    	if (data) {
				for ( var i in data) {
					jQuery(
							'<input type="hidden" name="' + i + '" value="'
									+ data[i] + '" />').appendTo(form);
				}
			}
	    	for (var i = 0; i < fileElementId.length; i ++) {
				var oldElement = jQuery('#' + fileElementId[i]);
				var newElement = jQuery(oldElement).clone();
				jQuery(oldElement).attr('id', fileElementId[i]);
				jQuery(oldElement).attr('name', fileElementId[i]);
				jQuery(oldElement).before(newElement);
				jQuery(oldElement).appendTo(form);
			}
	    	//set attributes
	    	jQuery(form).css('position', 'absolute');
	    	jQuery(form).css('top', '-1200px');
	    	jQuery(form).css('