Java struts2+jquery实现bootstrap的fileinput插件的文件上传

本文详细介绍了使用Bootstrap进行文件上传的流程。首先需导入相关包,包括bootstrap-fileinput及bootstrap和jquery的包。接着给出JSP页面代码,然后展示了js代码及上传成功后的回调函数。最后介绍了action里的处理逻辑,此流程可将文件放到文件夹,若要数据库记录可通过回调函数实现。

1、首先导入包

<script src="assets/scripts/back/uploadfile.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-fileinput/4.4.7/js/fileinput.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-fileinput/4.4.7/js/locales/zh.min.js"></script>                                                        <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap-fileinput/4.4.7/css/fileinput.css">  /*  css样式  */

注:实现还要导入bootstrap和jquery的包。


2、JSP页面

<div class="file-loading" >          /* 插件自带导入的css格式 */
      <input id="modifyfile" name="file" type="file">       /* name一定要有,方便action里面取值 */
</div>
<div id="modifyfile_error"></div>


3、js代码

$("#scene").fileinput({
        language : 'zh',
        showCaption : true,
        showUpload : true,
        showCancel : false,
        showRemove : false,
        maxFileSize : 2048,
        autoReplace: true,
        uploadUrl:"scene_addFile",  //上传文件路径  strutsaction名_方法名
        //uploadExtraData  //上传文件时额外传递的参数设置
        elErrorContainer : '#scene-file',  
        allowedFileExtensions : [ "txt"],
        showPreview :false,
        slugCallback : function(filename) {            /* 文件被选择后会调用到这个方法,可以在action里边定义一个String                                                                                                   fileFileName接受值,自己试过,删掉这方法后好像会收不到值  */
            return filename.replace('(', '_').replace(']', '_');
        }
    });
    $('#scene').on("fileuploaded", function(event, data, previewId, index) {      /* 上传成功后调用的回调函数 */
        var result = data.response; //后台返回的json  
        console.log('文件上传成功!'+result.fileAdress);
        $("#scenefile").val(result.fileAdress);
    });


4、acntion里面

public void addFile() throws Exception{
        String path = ServletActionContext.getServletContext().getRealPath("/");
        File tempfile = new File(path);    // 如果文件夹不存在创建
        if (!tempfile.exists()) {
            tempfile.mkdir();
        }
        final Map<String, Object> result = new HashMap<String, Object>();
        result.put("status", "success");
        try{
            if(file != null && fileFileName != null){         //判断是否有文件
                UploadUtil.upload(file ,fileFileName, path);    //自定义的类,方法在下面
            }
            result.put("fileAdress",fileFileName);
        }catch(Exception e){
            e.printStackTrace();
            result.put("status", "error");
            response.getWriter().print(new GsonBuilder().create().toJson(result));
        }finally{
            response.setCharacterEncoding("UTF-8"); 
            response.getWriter().print(new GsonBuilder().create().toJson(result));    //封装为json对象后传出
        }
    }

public static String upload(File file , String fileName ,String savaPath ) throws IOException{
        //文件上传路径
        String uploadfilePath = savaPath+"assets\\file\\";   //自己定
        System.out.println(uploadfilePath);
        File uploadfile = new File(uploadfilePath); 
        //判断文件夹是否存在,如果不存在则创建文件夹
        if (!uploadfile.exists()) {//先创建uploadfile文件夹
            uploadfile.mkdir();
        }
        File tempFile=new File(uploadfilePath, fileName); 
        FileOutputStream fos = new FileOutputStream(tempFile);
        InputStream input = new FileInputStream(file);
        // 一次30kb
        byte[] readBuff = new byte[1024 * 30];
        int count = -1;
        while ((count = input.read(readBuff, 0, readBuff.length)) != -1) {
            fos.write(readBuff, 0, count);
        }
        fos.flush();
        fos.close();
        input.close();
        return null;
    }

以上则为bootstrap的传文件流程,此流程只会将文件放到文件夹里,若要数据库记录,则可以通过回调函数,将文件名赋给jsp页面一隐藏文本框,然后跟随其他信息通过表单被提交。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值