Java ajax 上传文件(隐藏上传按钮方式)

本文介绍了如何在Java SpringMVC环境中,利用Ajax实现文件上传,并隐藏传统上传按钮,提供更友好的用户体验。前端代码与后端处理及配置进行了详细说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

记录以后可能会用到。

首先前端代码:

<div class="uploadbox">                                                 
    <input type="file" id="file" style="display:none" onChange="up()">                                              
    <button type="button" class="" id="test1" onclick="file.click()"> 
    <i class="layui-icon">&#xe67c;</i>上传文件</button>                                                                                                             
</div> 


//上传文档  具体实现
function up(){  
    var max=4*1024*1024;//4194304
    $("#loading2").show();
    var file = $("#file")[0].files[0]; //取值
    if(file && file.size>max){
        $("#loading2").hide(); //只是loading图可忽略
        alert("上传文件不能超过4M,请重新上传");
        return false;
    }               
       var fd = new FormData();  
       if (typeof(file) == "undefined") { //判断 可忽略
       alert("请添加文件"); 
       return false;
    }  
       var point = file.name.lastIndexOf(".");              
       var type = file.name.substr(point+1); //文件后缀名                             
       fd.append("file", file); //添加参数
       fd.append("fileType", type);//添加参数

        $("#loading").show();                  
            $.ajax({  
               type: 'post',  
               url: "http://"+IP+"/app/document/doUploadDocuments.do",  
               data: fd,  
               method:"post",xhrFields: {withCredentials: true},crossDomain: true, //跨域操作,可忽略
               cache: false,  
               processData: false,  //这些不能忽略
               contentType: false,  
           }).success(function (data) { 
            fNmame=data.msg;
            $("#loading2").hide();
            if(fNmame=="-1"){                       
                alert("上传失败"); 
                $("#file")[0].value="";//清空file的值 让他是个全新的fil以触发第二次的上传操作,不然上传相同的文件会不触发此方法
                return false;
            }
            if(fNmame=="-2"){
                alert("尚未分配服务,请申请"); 
                $("#file")[0].value="";//清空file的值 让他是个全新的file以触发第二次的上传操作
                return false;
            }               
           }).error(function () { 
            $("#loading2").hide();
               alert("上传失败");  
           });   


}

下面是JAVA后端的代码与配置
我用的SpringMVC 所以在mvc配置下加了这段

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <property name="defaultEncoding" value="UTF-8" />
   <!-- 指定所上传文件的总大小不能超过200KB,下面是字节。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
   <property name="maxUploadSize" value="204800"/>
   <!-- 指定上传文件的临时路径 --> 
</bean>
    /**
     * 上传文档
     * @param url
     * @param entity
     * @param request 注意file 与前段name同名
     * @return
     */
    @RequestMapping("doUploadDocuments.do")
    public Message doUploadDocuments(MultipartFile file,Document entity,HttpServletRequest request) {   
            String uuid=null;
            double originalFilesize = request.getContentLength();//获取源文件大小
            InputStream in;
        try {                        
                in=file.getInputStream();   //流  拿到流就好办了。直接写文件也好,干什么都行。           
                entity.setFileSize((int)originalFilesize);//文件大小                        
                uuid = app.upload(in,entity,getCurrentUser(), request); //这是跟业务有关的逻辑可忽略                                
                in.close();     
            } catch (Exception e) { 

            }
        if(uuid.equals("-1")) {
            buildResultError("转换出现错误", "-1");
        }
        if(uuid.equals("-2")){
            buildResultError("尚未分配服务,请申请", "-2");
        }                     
        return buildSuccess(uuid);
    }

好了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值