springMVC多文件异步上传

1.需要导入jar包 commons-fileupload.jar  commons-io.jar

2.springmvc需要添加的配置文件


	
		
		
		

	

3.form表单代码

取消

4.js中ajax异步请求代码

function uploadFun(){
	var formData = new FormData($("#uploadForm")[0]);
	$.ajax({
        url : "${pageContext.request.contextPath}/admin/tdupload/upload",
        type : 'POST',
        data : formData,
        processData : false,                 
        contentType : false,
        async : false,
        success : function(data) {
            if(data == "success"){
            	$("#tjdl").dialog("close");
            	refresh();
            }else{
            	$("#tjdl").dialog("close");
            	$.messager.alert(data);
            }
        },
        error : function(x){
        	$("#tjdl").dialog("close");
        	$.messager.alert("上传文件异常");
        }
	});
	
}

5.java控制器代码

@RequestMapping(value="/upload", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
	@ResponseBody
	public String fileUploadCon(@SessionModel Staff staff,
			@RequestParam(value = "file") MultipartFile[] files,HttpServletRequest request, 
			HttpServletResponse response,String tdh,String gsmc,String fType) throws Exception{
        
		String rootPath = this.properties.getProperty("server.dist");// 跟路径 E:\\
		String rootURI = this.properties.getProperty("server.uri");// 相对路径 /server
		String path =rootPath+ rootURI + "/"+tdh;
		try {
			for (MultipartFile file : files) {
				String fileName = file.getOriginalFilename();
				File filePath = new File(path, fileName);
				// 如果文件目录不存在,创建目录
				if (!filePath.getParentFile().exists()) {
					filePath.getParentFile().mkdirs();
					System.out.println("创建目录" + filePath);
				}
				// 写入文件
				file.transferTo(filePath);
				//保存上传记录
				TdFile tdFile=new TdFile();
				tdFile.setTdh(tdh);
				tdFile.setFileName(fileName);
				tdFile.setFilePath(filePath.getAbsolutePath());
				tdFile.setScr(staff.getName());
				String serverUrl=filePath.getAbsolutePath().substring(2).replaceAll("\\\\", "/");
				tdFile.setServerUrl(serverUrl);
				tdFile.setStatus(0);
				tdFile.setFileOrderId("ZSY"+new Date().getTime());
				tdFile.setFileType(fType);
				tdFile.setGsmc(gsmc);
				tdFileService.insertTdFile(tdFile);
			}
		} catch (Exception e) {
			return e.getMessage();
		}
		
        return "success";
	}

 

你可能感兴趣的:(springMVC多文件异步上传)