SpringMVC form表单 上传一个文件

前台.jsp文件

<body>

 <!--第一步:引入.js文件 ajaxSubmit需要jquery.form.js-->
    <script type="text/javascript"
    src="<%=basePath%>/resources/js/jquery.min.js"></script>
<script type="text/javascript"
    src="<%=basePath%>/resources/js/jquery.validate.min.js"></script>
<script type="text/javascript"
    src="<%=basePath%>/resources/js/jquery.form.js"></script>
    
    <!--第二步 新增表单区域开始:enctype="multipart/form-data" -->
    <form id="createForm" enctype="multipart/form-data">
        <ul>
            <li><label>标题:</label> <input type="text" class="input-box"
                placeholder="请输入标题" name="title"></li>

            <li><label>内容:</label> <textarea class="textarea-box"
                    name="content"></textarea></li>

            <li><label>上传附件:</label> <input type="file" class="img-btn"
                name="file"></li>

            <!-- 点击保存按钮提交form -->
            <li><input type="submit" class="btn save-btn" value="保存">
            </li>
        </ul>
    </form>
    <!--新增表单区域结束-->
</body>


<script>
    $("#createForm").validate({
        //做表单验证

        //验证成功后提交参数
        submitHandler : function(form) {
            ajaxSubmit();
        }

    });
    function ajaxSubmit() {
        
        /*用ajaxSubmit()方法提交文件*/
        $("#createForm").ajaxSubmit({
            type : 'post',
            url : "emergencyNotice/create",
            error : function() {//请求失败处理函数  
                alert("失败");
            },
            success : function(data) { //请求成功后处理函数。
               alert("成功");
            }
        });
    };
</script>

后台控制器.java文件

import java.io.IOException;
import javax.servlet.http.HttpSession;
import org.springframework.web.multipart.MultipartFile;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@ResponseBody
@RequiresPermissions("emergencyNotice:create")
@RequestMapping("/emergencyNotice/create")
public void createEmergencyNotice(EmergencyNotice emergencyNotice, MultipartFile file,
		HttpSession session) throws IOException {
       
     /*1处理实体类对象emergencyNotice,省略*/

     /*2处理文件*/
	String basePath = session.getServletContext().getRealPath("/"); // 获取基本路径

    /*如果文件不为空,保存文件*/ 
    if (file != null && !file.isEmpty()) {
	   String urlPath = HandleFile.saveFile(file, basePath); /*保存附件到本地*/ 

     } /*end if*/
}

这篇文章把提交文件和提交一个实体类(基本类型)放在了一起,但是对实体类的处理,省略了。想提醒一下:文件是可以和实体类(基本类型)一起提交到后台

这样提交,无论前台有没有提交文件,都不会出错的

HandleFile 中具体怎么保存文件的,参考
http://blog.csdn.net/dreamstar613/article/details/53841438

posted on 2017-05-12 11:49  dreamstar  阅读(245)  评论(0编辑  收藏  举报