bootstrap fileinput 完整例子(有后台java版)

这个插件主页地址是:http://plugins.krajee.com/file-input/demo
GitHub地址:https://github.com/kartik-v/bootstrap-fileinput

引入js:

<script src="${basePath }${pageContext.request.contextPath}/plugin/fileinput/js/fileinput.js"></script>
<!--配置中文,但是没有汉化成功,只能在配置里重写-->
<script src="${basePath }${pageContext.request.contextPath}/plugin/fileinput/js/locales/zh.js"></script>

引入css:

  <link rel="stylesheet" href="${basePath }${pageContext.request.contextPath}/plugin/fileinput/css/fileinput.css" type="text/css" />

假设要提交表单和上传图片一起

<label class="col-sm-2 control-label">图片上传</label>
//后台的接受名为file,要相同名字,id为初始化文件框
<input id="file-pic" name="file" type="file" multiple>
 <form id="form1">
     图片id<input type="text" name="id" id="picid" >
     图片名称:<input type="text" name="picName" >  
     <input type="button" id="savePic">保存</button>          
 </form>

在页面初始化一个inputFile,不要写成这样的$('#file-pic').fileinput('refresh',{..}),上传多张图的话,后面的图片会把前面的刷新掉,只上传最后一张图

$('#file-pic').fileinput({//初始化上传文件框
        showUpload : false,
        showRemove : false,
        uploadAsync: true,
        uploadLabel: "上传",//设置上传按钮的汉字
        uploadClass: "btn btn-primary",//设置上传按钮样式
        showCaption: false,//是否显示标题
        language: "zh",//配置语言
        uploadUrl: "BannerPicAction!addPicture.action",
        maxFileSize : 0,
        maxFileCount: 1,/*允许最大上传数,可以多个,当前设置单个*/
        enctype: 'multipart/form-data',
        //allowedPreviewTypes : [ 'image' ], //allowedFileTypes: ['image', 'video', 'flash'],
        allowedFileExtensions : ["jpg", "png","gif"],/*上传文件格式*/
        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}!",
        dropZoneTitle: "请通过拖拽图片文件放到这里", 
        dropZoneClickTitle: "或者点击此区域添加图片",
        //uploadExtraData: {"id": id},//这个是外带数据
        showBrowse: false,
        browseOnZoneClick: true,
        slugCallback : function(filename) {
            return filename.replace('(', '_').replace(']', '_');
        }
    });
    //上传文件成功,回调函数 
    $('#file-pic').on("fileuploaded", function(event, data, previewId, index) {
    var result = data.response; //后台返回的json
    //console.log(result.status);
    //console.log(result.id);
    $('#picid').val(result.id);//拿到后台传回来的id,给图片的id赋值序列化表单用
    //如果是上传多张图
    /*
    //计数标记,用于确保全部图片都上传成功了,再提交表单信息
    var fileCount = $('#file-pic').fileinput('getFilesCount');
    if(fileCount==1){
    $.ajax({//上传文件成功后再保存图片信息
        url:'BannerPicAction!savaForm.action',
        data:$('#form1').serialize(),//form表单的值
        success:function(data,status){
            ...
        },
        cache:false,                    //不缓存
    });
    }
    */
    $.ajax({//上传文件成功后再保存图片信息
        url:'BannerPicAction!savaForm.action',
        type:'post',
        dataType:'json',
        data:$('#form1').serialize(),//form表单的值
        success:function(data,status){
            if (status == "success") {

                if(data.status == "success"){//提交成功

                    //跳转回添加页面

                }else{
                    alert("添加失败,编码的错误!");
                }

                } else {
                    alert("添加失败,ajax请求返回失败!");
            }
        },
        cache:false,                    //不缓存
    });
    });

    $('#savePic').on('click',function (){// 提交图片信息 //
        //先上传文件,然后在回调函数提交表单
        $('#file-pic').fileinput('upload');

    }); 

后台代码部分:

@Action(value = "BannerPicAction")
@Scope("prototype")
@Results(value = {
        @Result(name=""),
})
public class BannerPicAction extends BaseAction{

    private File file;            //文件  
    private String fileFileName;  //文件名
    private String fileContentType; //文件类型
    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    省略getset方法

    /**
     * 接受表单的
     * @return
     * @throws Exception
     */
    public String savaForm() throws Exception{

        省略

        return null;
    }

    /**
     * 图片上传(可多个)
     * @return
     * @throws Exception
     */
    public String addPicture() throws Exception{
        //保存图片的文件夹路径(tomcat的项目目录下的-->shop/uploadfile)
        String path = ServletActionContext.getServletContext().getRealPath("/");
        File tempfile = new File(path); // 如果文件夹不存在创建
        if (!tempfile.exists()) {
            tempfile.mkdir();
        }
        System.out.println(path);
        PrintWriter out = null;
        //结果集
        final Map<String, Object> result = new HashMap<String, Object>();
        result.put("status", "success");
        try{
            List<PicVO> list = new ArrayList<PicVO>();//list里返回图片路径和缩略图路径
            if(file != null && fileFileName != null){//判断是否有文件
                UploadImgUtils.upload(file, fileFileName, path);//上传文件的类,
            }
                //首先保存图片地址(然后再有savaForm.action保存图片)
                BannerPic pic = bannerPicService.save(bannerPic);
                result.put("id",pic.getId());//返回图片信息ID,给图片上传更新用
            }
            out = this.response.getWriter();
            response.setContentType("application/json");
        }catch(Exception e){
            e.printStackTrace();
            result.put("status", "error");
            out.write(GsonUtils.GSON.toJson(result));
            log.error(e.getMessage(), e);
        }finally{
            out.write(GsonUtils.GSON.toJson(result));
            out.close();
        }
        return null;
    }
}

也给出上传文件代码:

public static List<PicVO> upload(File file , String fileName ,String savaPath ) throws IOException{

        SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
        String dateNow = formatDate.format(new Date());
        ///uploadfile/以日期为文件夹名,保存进数据库的相对路径
        String relativePath = "\\uploadfile\\"+dateNow; 
        String uploadfilePath = savaPath+"\\uploadfile"; //uploadfile文件夹
        //(tomcat目录下的绝对路径-->shop/uploadFile/以日期为文件夹名)
        String path = savaPath+relativePath;
        System.out.println(path);
        //保存进数据库的相对路径
        //String relativePath = savaPath.substring(savaPath.lastIndexOf("shop"))+"\\"+dateNow; 
        File uploadfile = new File(uploadfilePath); 
        //判断文件夹是否存在,如果不存在则创建文件夹
        if (!uploadfile.exists()) {//先创建uploadfile文件夹
            uploadfile.mkdir();
        }
        File tempfile = new File(path); //判断文件夹是否存在,如果不存在则创建文件夹
        if (!tempfile.exists()) {//然后创建以日期为文件夹名的文件夹
            tempfile.mkdir();
        }
        List<PicVO> list = new ArrayList<PicVO>();//图片临时对象里面属性是(picUrl,ThumbPicUrl)

            PicVO picVO = new PicVO(); //新建临时对象
            // 采用时间+UUID的方式随即命名
            String UUIDFileName = java.util.UUID.randomUUID().toString();
            // 保存在tomcat中的文件名
            String newFileName = UUIDFileName+ fileName.substring(fileName.lastIndexOf(".")); 
            File tempFile=new File( path, newFileName); 
            //FileUtils.copyFile(file, tempFile);//保存文件
            //File tempFile=new File(newFileName);
            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();

            list.add(picVO);
        }
        return list;
    }
  • 7
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值