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( "上传出错了" );
         }
 
     }

转载于:https://www.cnblogs.com/qianzf/p/11362116.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值