springmvc Ajax表单上传文件案例

1.html

<form id='formId' method='post'  enctype="multipart/form-data">

    <table>
        <tr>
            <td class='n_type'>名称td>
            <td><input id='n_project_name' name='project_name'>td>
        tr>
        <tr>
            <td class='n_type'>文件:td>
            <td>
               <input id="lefile" name="lefile" type="file" style="display:none">
               <div class="input-append">
                 <input  id="file_name" name="file_name" type="text" >
                 <a class="btn" onclick="$('input[id=lefile]').click();" >上传a>
                div>
             td>
        tr>
        table>
    form>

2.js

  $('input[id=lefile]').change(function() {
            $('#file_name').val($(this).val());
   });

    $("#flowconfirm").click(function() {

            $.ajax({
                cache: true,
                type: "POST",
                url:url,
                data: new FormData(document.getElementById("formId")),
                // 告诉jQuery不要去处理发送的数据
                processData : false,
                // 告诉jQuery不要去设置Content-Type请求头
                contentType : false,
                error: function(request) {
                    alert("Connection error");
                },
                success: function(data) {

                }
            });
        });

3.controller

  @RequestMapping(value = "/addProject" , method = RequestMethod.POST)
   @ResponseBody
    public Object addProject(Project project , HttpServletRequest request){
        //获取上传的文件
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("lefile");
        String fileName = file.getOriginalFilename();
        project.setFile_name(fileName);
        //保存
        try {
            File targetFile = new File(projectFilePath, fileName);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

4.spring.xml

<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        
        <property name="maxUploadSize" value="10240000" />
        <property name="resolveLazily" value="true" />
        <property name="defaultEncoding" value="UTF-8" />
    bean>

你可能感兴趣的:(框架-Spring)