Ajax上传文件,前端数据获取,SpringMVC后台数据接收

2 篇文章 0 订阅
1 篇文章 0 订阅

Ajax上传文件,前端数据获取,SpringMVC后台数据接收


目录

  • 需求前期准备
  • SpringMVC.xml配置
  • Ajax前端数据获取
  • SpringMVC后端接收数据

  • 1.需求前期准备

    文件上传下载需要的SpringMVC相关jar包:

    com.springsource.org.apache.commons.fileupload-1.2.0.jar
    com.springsource.org.apache.commons.io-1.4.0.jar

    注:可以选择高版本jar包,不过此版本是当前比较常用的jar包.
    jar包下载地址:
    https://download.csdn.net/download/marksunshine/10466580


    2.SpringMVC.xml配置
        <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
        <!-- 需要apache common.fileupload jar包 -->  
        <bean id="multipartResolver"    
            class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
            <!-- 默认编码 -->  
            <property name="defaultEncoding" value="utf-8" />    
            <!-- 文件大小最大值 -->  
            <property name="maxUploadSize" value="10485760000" />    
            <!-- 内存中的最大值 -->  
            <property name="maxInMemorySize" value="40960" />    
        </bean>

    3.Ajax前端数据获取

    两种方式进行数据传输:
    方法1:直接使用form表单提交

    <form id="fileForm" action="file/fileupload.action" method="post" enctype="multipart/form-data">
       <input type="text" name="username">
       <input type="text" name="age">
       <input type="text" name="phoneNumber">
       <input type="file" name="file">  
       <button type="submit" >保存</button>
    </form>

    方法2:使用采用了FormData的传输方式
    formData使用参考手册:https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/FormData

    form表单:

    <form id="fileForm" name="fileForm" action="#" onsubmit="return false" method="post" enctype="multipart/form-data">
       <input type="text" name="username">
       <input type="text" name="age">
       <input type="text" name="phoneNumber">
       <input type="file" name="file">  
       <button type="button" onclick="getComtent()">保存</button>
    </form>

    数据获取以及使用Ajax传递方法1:

    <script type="text/javascript">
            //获取编辑内容
            function getComtent() {
                //用户名
                var username = document.fileForm.username.value;    
                //年龄
                var age= document.fileForm.age.value;
                //电话号码
                var phoneNumber= document.fileForm.phoneNumber.value;
                //文件
                var file = document.fileForm.file.files[0];
                //ormData是Html5新加进来的一个类,可以模拟表单数据
                var fm = new FormData();
                fm.append('username', username );
                fm.append('age', age);
                fm.append('phoneNumber', phoneNumber);
                fm.append('file', articleClass);
    
                 //进行Ajax请求
                 $.ajax({
                     //几个参数需要注意一下
                     type: "POST",//方法类型
                     dataType: "json",//预期服务器返回的数据类型,可以不设置
                     url: "file/fileupload.action" ,//url
                     data: fm,
                     async: false,  
                     cache: false,
                     contentType: false, //禁止设置请求类型
                     processData: false, //禁止jquery对DAta数据的处理,默认会处理
                     success: function (result) {
                         console.log(result);//打印服务端返回的数据(调试用)
                         if (result.isSuccess) {
                             //跳转页面
                             //window.location.href="user/personalDesk.action";
                         }
                     },
                     error : function() {
                         alert("异常!");
                     }
                 });
    </script>

    数据获取以及使用Ajax传递方法2:

    <script type="text/javascript">
            //获取编辑内容
            function getComtent() {
                var fm = new FormData($( "#fileForm" )[0]);
                 //进行Ajax请求
                 $.ajax({
                     //几个参数需要注意一下
                     type: "POST",//方法类型
                     dataType: "json",//预期服务器返回的数据类型,可以不设置
                     url: "file/fileupload.action" ,//url
                     data: fm,
                     async: false,  
                     cache: false,
                     contentType: false, //禁止设置请求类型
                     processData: false, //禁止jquery对DAta数据的处理,默认会处理
                     success: function (result) {
                         console.log(result);//打印服务端返回的数据(调试用)
                         if (result.isSuccess) {
                             //跳转页面
                             //window.location.href="user/personalDesk.action";
                         }
                     },
                     error : function() {
                         alert("异常!");
                     }
                 });
    </script>
    4.SpringMVC后端接收数据

    后台接收方式1:

    @RequestMapping("/file/fileupload.action")
        @ResponseBody
        public Map<String,Object> createArticle(ModelMap map,HttpServletRequest request) {
            //返回信息集合
            Map<String,Object> resultMap = new HashMap<String, Object>();
            try {
                //解析请求中的数据  
                MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest) request;  
                MultipartFile file = mpRequest.getFile("file");
                //上传文件的真实名称  
                String name = file.getOriginalFilename(); 
                System.out.println("----------articleFile-name----------");
                System.out.println(name);
    
                resultMap.put("result", "操作成功");
                resultMap.put("data", "");
                resultMap.put("isSuccess", true);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return resultMap;
        }

    后台接收方式2:

    @RequestMapping("/file/fileupload.action")
        @ResponseBody
        public Map<String,Object> createArticle(HttpServletRequest request,
                @RequestParam(value="file") CommonsMultipartFile file,
                @RequestParam(value = "username") String username,
                @RequestParam(value = "age") String age,
                @RequestParam(value = "phoneNumber") String phoneNumber
                ) {
            //返回信息集合
            Map<String,Object> resultMap = new HashMap<String, Object>();
            try {
                System.out.println("----------Filename----------");
                System.out.println(file.getOriginalFilename());
                System.out.println("----------username----------");
                System.out.println(username);
                System.out.println("----------phoneNumber----------");
                System.out.println(phoneNumber);
                System.out.println("----------age----------");
                System.out.println(age);
    
                resultMap.put("result", "操作成功");
                resultMap.put("data", "");
                resultMap.put("isSuccess", true);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return resultMap;
        }
  • 4
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值