129-跨域(二)ajax提交form表单(支持跨域文件上传)

客户端:

  1. 引入js
    <script src="/javascripts/jquery.min.js"></script>
    <script src="/javascripts/jquery.form.js"></script>
    

js文件下载地址 链接: http://pan.baidu.com/s/1qY3tbDq 密码: 7vxa

  1. form表单:
    <form id="goodsCreateForm" action="/upload" method="post" enctype="multipart/form-data">
      <div id="tip" class="alert alert-warning alert-dismissible" role="alert">
        <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
        <strong>提示!</strong> 
        <span name="content">每一项都是必填的.</span>
      </div>
      <div class="form-group">
        <label for="inputGoodsName">课程名称 </label>
        <input type="text" class="form-control" name="name" id="inputGoodsName" placeholder="输入课程名称">
      </div>
      <div class="form-group">
        <label for="inputGoodsPicture">课程封面 </label>
        <input type="file" name="picture" id="inputGoodsPicture" >
      </div>
      <button type="submit" id="goodsCreateSubmit" class="btn btn-primary">添加 </button>
    </form>
    
  2. js编写
    <script>
      // prepare the form when the DOM is ready
      $(document).ready(function() {
          var options = {
              //target:        '#output2',   // target element(s) to be updated with server response
              beforeSubmit:  showRequest,  // pre-submit callback
              success:       showResponse  // post-submit callback
    
              // other available options:
              //url:       url         // override for form's 'action' attribute
              //type:      type        // 'get' or 'post', override for form's 'method' attribute
              ,dataType:  'json'        // 'xml', 'script', or 'json' (expected server response type)
              //clearForm: true        // clear all form fields after successful submit
              //resetForm: true        // reset the form after successful submit
    
              // $.ajax options can be used here too, for example:
              //timeout:   3000
          };
    
          // bind to the form's submit event
          $('#goodsCreateForm').submit(function() {
              // inside event callbacks 'this' is the DOM element so we first
              // wrap it in a jQuery object and then invoke ajaxSubmit
              $(this).ajaxSubmit(options);
    
              // !!! Important !!!
              // always return false to prevent standard browser submit and page navigation
              return false;
          });
      });
    
      // pre-submit callback
      function showRequest(formData, jqForm, options) {
          $('#tip span[name="content"]').html('提交中...');
          // here we could return false to prevent the form from being submitted;
          // returning anything other than false will allow the form submit to continue
          return true;
      }
    
      // post-submit callback
      function showResponse(data)  {
          $('#tip span[name="content"]').html(data.msg);
          if(data.error == 0){
            location.href="/goods/index";
          }
          
      }
    </script>
    

服务器端(Nodejs)

  1. 安装组件
    npm install multiparty --save
    npm install mime --save
    
  2. 路由
    "/upload" : {
        "post" : "usercontroller#upload"
    },
    
  3. usercontroller文件
    //引入 multiparty模块处理from文件上传
    var multiparty = require('multiparty');
    //引入 mime模块
    const mime = require('mime');
    
    module.exports = {
      //用户数据文件上传
      upload : function(req, res){
        //设置全局访问(处理跨域)
        res.setHeader("Access-Control-Allow-Origin", "*");
        res.setHeader("Access-Control-Allow-Methods", "POST");
    
        //处理from表单 (支持multipart/form-data文件上传)
        var form = new multiparty.Form();
        
        // emitted from the `form` and the `part`.
        form.on('error', function(err) {
          console.log('Error parsing form: ' + err.stack);
        });
     
        //接收数据完成
        form.parse(req, function(err, fields, files) {
          //打印上传结果
          console.log(fields);
          console.log(files);
        }
      }
    }
    

推荐阅读更多精彩内容