zoukankan      html  css  js  c++  java
  • form表单文件上传提交且接口回调显示提交成功

    前端:
    <form method="post" enctype="multipart/form-data" id="formSubmit">
          <div class="row">
               <div class="col-lg-12" style="padding-left:25px;padding-top: 5px">
                    <label>请选择文件</label>
                    <input type="file" name="file" title="点击选择文件" multiple="" accept="*/*" class="form-control">
               </div>
          </div>
          <div class="row">
               <div style="padding-left:25px;padding-top:10px">
                    <input type="submit" class="btn btn-primary">
               </div>
          </div>
    </form>
    复制代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    JS:
    $('#formSubmit').submit(function (event) {
            //首先验证文件格式
            var fileName = $(this).find("input[name=file]").val();
            if (fileName === '') {
                alert('请选择文件');
                return;
            }
            // mulitipart form,如文件上传类
            var formData = new FormData(this);
            $.ajax({
                async: false,
                type: "POST",
                url: "/upload",
                data: formData,
                dataType: "JSON",
                mimeType: "multipart/form-data",
                contentType: false,
                cache: false,
                processData: false,
                success: function (data) {
                    if (data.success) {
                        layer.alert("上传成功")
                    } else {
                        layer.alert(data.error)
                    }
                }
            });
            return false;
        });

      js代码的最后需要return false 防止表单重复提交,刷新页面。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    java:
     @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
        @ResponseBody
        public SimpleAjaxResponse uploadSingleFile(HttpServletRequest request, Model model) {
            try {
                DefaultMultipartHttpServletRequest httpServletRequest = (DefaultMultipartHttpServletRequest) request;
                MultipartFile multipartFile = httpServletRequest.getFile("file");
                return new SimpleAjaxResponse(true);
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
                e.printStackTrace();
                return new SimpleAjaxResponse("上传出错了");
            }
     
        }
  • 相关阅读:
    软工实践寒假作业2
    nginx前端代理配置文件
    个人作业——软件工程实践总结&个人技术博客
    个人作业——软件评测
    结对第二次作业——某次疫情统计可视化的实现
    结对第一次—疫情统计可视化(原型设计)
    软件工程实践寒假作业(2/2)
    软工实践寒假作业(1/2)
    毕设11.2
    毕设计划(11.1-11.8)
  • 原文地址:https://www.cnblogs.com/qianzf/p/11362116.html
Copyright © 2011-2022 走看看