加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajaxfileupload.js+springMVC实现无刷新文件上传

发布时间:2020-12-16 00:58:41 所属栏目:百科 来源:网络整理
导读:js部分用ajaxfileupload.js的方法ajaxfileupload.js是依赖jquery的,所以要引入jquery。 js代码: function upload(){var fileName = $(this).val(); $.ajaxFileUpload({url:rootPath+"/member/upload",secureuri:false,fileElementId:'busiAttachment',data

js部分用ajaxfileupload.js的方法ajaxfileupload.js是依赖jquery的,所以要引入jquery。

js代码:

 function upload(){
	var fileName = $(this).val();
	 $.ajaxFileUpload({
			url:rootPath+"/member/upload",secureuri:false,fileElementId:'busiAttachment',dataType:'json',success:function(data){
				
			}
		});
}

其中busiAttchment是<input type="file" id="busiAttchment" name="file" />的id,是必需的。input的name也是必需的,controller里面需要。

然后是controller里面的内容。

@RequestMapping(value = "/upload",method = RequestMethod.POST)
	public String upload(HttpServletRequest request,HttpServletResponse response) throws FileUploadException,IOException{
		DefaultMultipartHttpServletRequest defaultRequest = (DefaultMultipartHttpServletRequest)request;
		MultiValueMap<String,MultipartFile> fileMap =  defaultRequest.getMultiFileMap();
		List<MultipartFile> fileList = fileMap.get("file");
		MultipartFile file = fileList.get(0);
		WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();   
        ServletContext servletContext = webApplicationContext.getServletContext(); 
        String dirPath = servletContext.getRealPath("/WEB-INF/upload/");
        File dir = new File(dirPath);
        if(!dir.exists()){
        	dir.mkdir();
        }
        String filePath = dirPath+"/"+(new Date().getTime())+file.getOriginalFilename();
		File resultFile = inputstreamtofile(file.getInputStream(),filePath);
		Map<String,String> result = new HashMap<String,String>();
		result.put("filePath",resultFile.getPath());
		String jsonResult = JsonUtil.toJsonString(result);
		return returnJson(response,jsonResult);
	}
其中JsonUtil.toJsonString()和returnJson都是其他jar包里的方法,是公司里其他人提供的。主要就是为了返回json串。pw.wirte(json)这样的方法写。

inputstreamtofile方法:

public File inputstreamtofile(InputStream ins,String fileName) {
		File file = new File(fileName);
		try {
			OutputStream os = new FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer,8192)) != -1) {
				os.write(buffer,bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return file;
	}




在写的过程中遇到的问题:

1、一开始用普通的文件上传的方法,就是在servlet中直接写的那种通用方法:DiskFileItemFactory和ServletFileUpload写的那种。但是在List<?> item = upload.parseRequest(request);之后item为空。网上有解决struts2遇到这个问题的办法,说是request转换为MultipartHttpServletRequest类型的了,只要百度upload.parseRequest(request);返回空结果基本上都是struts2的解决方案。但是在springMVC中,request已经是DefaultMultipartHttpServletRequest类型的了,DefaultMultipartHttpServletRequest里包含上传文件的信息,获取方法看上面的代码。

2、其中有获取realPath的地方,一般在servlet中可以直接用this.servletContext().getRealPath()获取,但是在controller中不行,一开始用的方法是request.getSession().getServletContext().getRealPath("/")。但是报了个共享session不能用此方法。然后就用

ServletContext servletContext = webApplicationContext.getServletContext(); 
        String dirPath = servletContext.getRealPath("/WEB-INF/upload/");

这个来解决了。


这么一个小小的文件上传,没有任何验证,用掉了我几乎一天的时间,看来还是自己各方面知识掌握的不全面。还有很多药学习啊!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读