LayUI文件上传案例

1、前端页面代码

2.后端java代码

@ResponseBody
	@RequestMapping("batchAddWhiteList")
	public String batchAddWhiteList(HttpServletRequest request){
		ModelAndView mv = new ModelAndView();
		mv.setView(Jackson2Util.jsonView());
		CommonsMultipartResolver multipartResolver = 
        		new CommonsMultipartResolver(request.getSession().getServletContext());
		//检查form中是否有enctype="multipart/form-data"
		
		JSONObject jsonObject = new JSONObject();
        if(multipartResolver.isMultipart(request))
        {
            //将request变成多request
            MultipartHttpServletRequest multiRequest = 
            		(MultipartHttpServletRequest)request;
            
            //获取multiRequest中所有的文件名
            Iterator iter = multiRequest.getFileNames();
            while(iter.hasNext()){
                //一次遍历所有的文件
                MultipartFile file = multiRequest.getFile(iter.next().toString());
                
                if(null!= file && file.getSize()>20*1024*1024) {
                	
                	jsonObject.put("msg", "传输文件过大,上传失败!");
                }
                else if(file!=null){
                	String result = null;
					try {
						result = vehicleWhitelistService.batchImportVehicleWhitelistByXls(file);
						if("yes".equals(result)) {
							jsonObject.put("msg", true);	
						}else {
							jsonObject.put("msg", result);
						}
						
					} catch (Exception e) {
						jsonObject.put("msg", result);
						logger.error(result);
					}
					
                }
            }
        }
		
		return jsonObject.toString();
	}

3.需要注意的地方 :

后端代码的返回值应该是json格式,否则会报错。----顾,应该在后端java代码的controller添加@ResponseBody注解

如图

你可能感兴趣的:(layui)