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

本文参考: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=" " οnclick="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;
}

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


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值