SpringMVC+ajaxFileUpload 上传文件

在ie内核的低版本浏览器中会出现问题,在返回的Json数据中会自动加上<pre></pre>或者<pre style="word-wrap: break-word; white-space: pre-wrap;"></pre>导致解析不成功。


JS:

//执行上传文件操作的函数
			$.ajaxFileUpload({
				//处理文件上传操作的服务器端地址(可以传参数,已亲测可用)
				url : '${pageContext.request.contextPath}/upload/fileUpload',
				secureuri : false, //是否启用安全提交,默认为false
				fileElementId : 'fileupload', //文件选择框的id属性
				dataType : 'text', //服务器返回的格式,可以是json或xml等
				success : function(data, status) { //服务器响应成功时的处理函数
					data = data.replace("<PRE>", ''); //ajaxFileUpload会对服务器响应回来的text内容加上<pre>text</pre>前后缀
					data = data.replace("</PRE>", '');
					data = data.replace("<pre>", '');
					data = data.replace("</pre>", ''); //本例中设定上传文件完毕后,服务端会返回给前台[0`filepath]
					if(data.indexOf("pre")>0){//对ie/360等浏览器会/ajaxFileUpload会对服务器响应回来的text内容加上<pre style="word-wrap: break-word; white-space: pre-wrap;"> 用正则替换下
						var reg = /<pre.+?>(.+)/g;
						var result = data.match(reg);
						data = RegExp.$1;
					}
					
					if (data.substring(0, 1) == 0) { //0表示上传成功(后跟上传后的文件路径),1表示失败(后跟失败描述)
						$("#attachmentPath").val(data.substring(2));
						$('#result').html("附件上传成功<br/>");
					} else {
						$('#result').html('附件上传失败,请重试!!');
					}
				},
				error : function(data, status, e) { //服务器响应失败时的处理函数
					$('#result').html('附件上传失败,请重试!!');
				}
			});


后台:

@RequestMapping("fileUpload")
	public void fileUpload(@RequestParam MultipartFile[] myfiles, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// 这里实现文件上传操作用的是commons.io.FileUtils类,它会自动判断/upload是否存在,不存在会自动创建
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
		java.util.Date date = new java.util.Date();
		String time = sdf.format(date);
		String realPath = request.getSession().getServletContext().getRealPath(uploadFolderName);
		// 设置响应给前台内容的数据格式
		response.setContentType("text/plain; charset=UTF-8");
		// 设置响应给前台内容的PrintWriter对象
		PrintWriter out = response.getWriter();
		// 上传文件的原名(即上传前的文件名字)
		//String originalFilename = null;
		String newImgPath = null;
		// 如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解
		// 如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且要指定@RequestParam注解
		// 上传多个文件时,前台表单中的所有<input
		// type="file"/>的name都应该是myfiles,否则参数里的myfiles无法获取到所有上传的文件
		for (MultipartFile myfile : myfiles) {
			if (myfile.isEmpty()) {
				out.print("1`请选择文件后上传");
				out.flush();
			} else {
				//originalFilename = myfile.getOriginalFilename();
				//System.out.println("文件原名: " + originalFilename);
				//System.out.println("文件名称: " + myfile.getName());
				//System.out.println("文件长度: " + myfile.getSize());
				//System.out.println("文件类型: " + myfile.getContentType());
				//System.out.println("========================================");
				String imgPath = myfile.getOriginalFilename();

				// imgPath为原文件名
				int idx = imgPath.lastIndexOf(".");
				// 文件后缀
				String extention = imgPath.substring(idx);

				java.util.Date dt = new java.util.Date(System.currentTimeMillis());
				SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
				String times = fmt.format(dt);

				// 新的文件名(日期+后缀)
				newImgPath = times + extention;
				try {

					// 这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉
					// 此处也可以使用Spring提供的MultipartFile.transferTo(File
					// dest)方法实现文件的上传
					File targetFile = new File(realPath + "/" + time, newImgPath);
					if (!targetFile.exists()) {
						targetFile.mkdirs();
					}
					// 保存
					myfile.transferTo(targetFile);
				} catch (IOException e) {
					System.out.println("文件[" + newImgPath + "]上传失败,堆栈轨迹如下");
					e.printStackTrace();
					out.print("1`文件上传失败,请重试!!");
					out.flush();
				}
			}
		}
		out.print("0`" + request.getContextPath() + uploadFolderName + time + "/" + newImgPath);
		out.flush();
	}


你可能感兴趣的:(springMVC,ajaxFileUpload)