ajax传送表单中的文件之前后端实现

来源:互联网 发布:tensorflow支持显卡 编辑:程序博客网 时间:2024/05/22 02:01

本文参考:http://www.cnblogs.com/zhuxiaojie/p/4783939.html

这里我使用的是第二种方式。

首先,导入Jquery.form.js,这就会非常方便了。

使用$("#form").ajaxSubmit();语句就可以把表单数据传到后台了。

HTML代码:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><script type="text/javascript" src="../../js/jquery-3.2.1.js"></script><script type="text/javascript" src="jquery.form.js"></script></head><body><form id="signupListImportForm" class="import-file-form" enctype="multipart/form-data"><input type="text" name="userId" /> <input type="text" name="userName" /><input type="text" name="idCard" />     <input type="file" name="image" id="excelFile" style="width:160px" value="选择文件"><input class="fabu_button_e margin-right-20" type="button" value="导入线下报名" inited=" " onclick="submitExcel() "></form></body><span style="font-size:14px;"><script type="text/javascript">function submitExcel() {var option = {url : "http://localhost:8080/SSS/authentication/person",type : 'POST',dataType : "json",clearForm: true,success : function(data) {if (data.code == "001") {console.info("success!")}if (data.code == "002") {console.info("fail!")}}};$("#signupListImportForm").ajaxSubmit(option);return false;}</script></span></html>
JAVA代码

@RequestMapping(method=RequestMethod.POST, value="/person")@ResponseBody public BaseResult  courseSignupListImport(@RequestParam("image") MultipartFile image,HttpServletRequest request, HttpServletResponse response) throws IOException{BaseResult baseResult=new BaseResult();System.out.println(request.getParameter("userName"));String pathRoot="C:";String path="";if(!image.isEmpty()){//生成uuid作为文件名称String uuid=UUID.randomUUID().toString().replaceAll("-", "");//获得文件类型String contentType=image.getContentType();//获得文件后缀名称String imageType=contentType.substring(contentType.indexOf("/")+1);path="/person/"+uuid+"."+imageType;image.transferTo(new File(pathRoot+path));baseResult.setCode(Constants.SUCCESS);baseResult.setMessage("上传成功");baseResult.setObject(uuid+"."+imageType);}return baseResult;}

这样就可以把用户上传的文件保存在后台指定的路径,并且对还能对表单中的其他数据进行操作了!


原创粉丝点击