ajax如何提交form表单 formData,包含文件上传,以及ssm后台接收

<form id="add" method="post" enctype="multipart/form-data">
        <label>书名:</label>
        <input class="easyui-validatebox" type="text" name="bookName" id = "bookName" required="true">
        <label>作者:</label>
        <input class="easyui-validatebox" type="text" name="authorName" id="authorName" required="true">
        <lebel>封面:</lebel>
        <input type="file" name="file" id="file" />
    <div class="submit">
        <input type ="button" value="提交" id = "addSubmit">
    </div>
</form>

我们可以采用formdata进行表单数据的提交: 

通过formData获取form的Id进而获取form表单中的值,

那么如何获取formdata中的参数值呢

可以通过 var bookName = formData.getname("bookName"),查看值, name为要查看的name名

 

这样我们就能够获取到file了,那么问题来了,如何在后台接收呢

方法中参数MutipartFile file就行

可以通过打印file.getOriginalFilename()获取到前台传来的参数

 

 

首先,在前端页面上添加文件上传的表单,代码如下: ```html <form id="uploadForm" enctype="multipart/form-data"> <input type="file" name="file"/> <input type="button" value="上传" onclick="uploadFile()"/> </form> ``` 然后,在JavaScript代码中编写上传文件的函数,使用Ajax方式上传文件。代码如下: ```javascript function uploadFile() { var formData = new FormData($("#uploadForm")[0]); $.ajax({ url: "uploadFile", type: "POST", data: formData, contentType: false, processData: false, success: function (data) { alert("上传成功!"); }, error: function (xhr) { alert("上传失败!"); } }); } ``` 接着,在Spring MVC的Controller中添加文件上传的处理方法,代码如下: ```java @RequestMapping(value = "/uploadFile", method = RequestMethod.POST) @ResponseBody public String uploadFile(HttpServletRequest request) throws IOException { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile file = multipartRequest.getFile("file"); String fileName = file.getOriginalFilename(); String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"; File dest = new File(filePath + fileName); if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } file.transferTo(dest); return "success"; } ``` 最后,需要在Spring MVC的配置文件中添加以下配置,以支持文件上传: ```xml <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"/> <property name="maxUploadSize" value="104857600"/> <property name="maxInMemorySize" value="4096"/> </bean> ``` 其中,maxUploadSize表示上传文件的最大大小,单位为字节。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值