Ajax发送multipart / form-data

时间:2014-12-16 09:14:38

标签: javascript jquery ajax spring-mvc html-form

我的HTML代码:

<form:form name="vcfForm" id="vcfForm" method="post" enctype="multipart/form-data" action="../acquaintance/readingContactsFromVcfFile"></form:form>

<input type="file" name="vcfFile" id="vcfFile" form="vcfForm" >
    <button type="button" name="vcfSubmit" id="vcfSubmit" form="vcfForm">Upload</button>

我的控制器:

@RequestMapping(value = { "/readingContactsFromVcfFile" }, method = RequestMethod.POST)
public @ResponseBody
ModelMap readContactsFromVcfFile(@RequestParam("vcfFile") MultipartFile file, HttpServletRequest request) throws UserServiceException {
    ModelMap modelMap = new ModelMap();
  *********************code*****************
  modelMap.addAttribute("message", "success");
  return modelMap;
}

我的jquery代码:

 $(document).on('click','#vcfSubmit', function() {
                        var vcfData = new FormData(); 
                        vcfData.append('files[]', $('#vcfForm').get(0).files[0]);
                        $.ajax({
                            url : "../acquaintance/readingContactsFromVcfFile?vcfFile="+vcfData,
                            type : "post",
                            cache : false,
                            processData: false,
                            contentType: false,
                            success : function(data) {
                            alert(data.message);                                        
                            }
                            });   
                    });  

我的问题是,当我点击提交按钮时,页面将提交并返回消息&#34;成功&#34;显示在页面中。 我希望在使用ajax提交表单或传递文件时不刷新页面。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

html代码:

<form name="vcfForm" id="vcfForm" method="post" enctype="multipart/form-data" ></form>
<input type="file" name="vcfFile" id="vcfFile" form="vcfForm" >
    <button type="button" name="vcfSubmit" id="vcfSubmit" form="vcfForm">Upload</button>

控制器代码:

@RequestMapping(value = { "/readingContactsFromVcfFile" }, method = RequestMethod.POST)
public @ResponseBody
ModelMap readContactsFromVcfFile(@RequestParam(value = "vcfFile") MultipartFile file, HttpSession session) throws UserServiceException {
    ModelMap modelMap = new ModelMap();
    modelMap.addAttribute("message", "message");
    return modelMap;
}

jquery代码:

$(document).on('click','#vcfSubmit',function(){
                         var vcfData = new FormData($('#vcfForm')[0]); 
                          $.ajax({
                                url : "../acquaintance/readingContactsFromVcfFile?vcfFile="+vcfData,
                                type : "post",
                                data : vcfData,
                                processData: false,
                                contentType: false,
                                cache : false,
                                success : function(data) {
                                }
                            });   
                    }); 

每件事情都很好。