<!-- 七牛 --> <dependency> <groupId>com.qiniu</groupI <artifactId>qiniu-java-sdk</artifactId> <version>7.2.11</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.3.1</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.6.2</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.qiniu</groupId> <artifactId>happy-dns-java</artifactId> <version>0.1.4</version> <scope>compile</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>
<!-- 七牛 end-->
最后两个依赖文件一定要有!!!!!!!!切记!!!!
/** * @ClassName: QiniuUtils * @Description: 七牛操作工具类 * */ public class QiniuUtils { //Access key private static final String ACCESS_KEY = "********"; //Secret key private static final String SECRET_KEY = "******"; //bucket name private static final String BUCKET_NAME = "七牛空间名称"; //访问前缀 private static final String CDN_DOMAIN_NAME = "http://****"; //上传根目录 private static final String IMG_UPLOAD_PATH = "bigData/"; //构造一个带指定Zone对象的配置类 //华东:Zone.zone0()、华北:Zone.zone1()、华南:Zone.zone2() private static final Configuration cfg = new Configuration(Zone.zone0()); private static final UploadManager uploadManager = new UploadManager(cfg); /** * 上传图片到七牛云 * 并返回图片URL * @param file * @return */ public static String uploadImg2QiNiu(MultipartFile file) throws IOException { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH:mm:ss.SSS"); String key = IMG_UPLOAD_PATH +sdf.format(new Date())+file.getOriginalFilename(); try { Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY); String upToken = auth.uploadToken(BUCKET_NAME); Response response = uploadManager.put(file.getInputStream(), key, upToken,null, null); //解析上传成功的结果 DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); return CDN_DOMAIN_NAME + putRet.key; } catch (QiniuException e) { Response r = e.response; // 请求失败时打印的异常的信息 //System.out.println(r.toString()); try { // 响应的文本信息 System.out.println(r.bodyString()); } catch (QiniuException qe) { e.printStackTrace(); } return "上传图片异常!"; } } }
下面是上传的方法
/** * 上传图片 * @param request * @return */ @Override public Map<String, Object> upImgInfo(HttpServletRequest request) { Map<String, Object> map = new HashMap<String, Object>(); //初始化通用multipart解析器 CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); //判断请求中是否有文件上传 if (!multipartResolver.isMultipart(request)) { //请求为空,直接返回 map.put("success",false); map.put("msg","上传图片失败!"); } //解析请求,将文件信息放到迭代器里 MultipartHttpServletRequest multiRequest = null; try { multiRequest = (MultipartHttpServletRequest) request; }catch (Exception e){ map.put("success",false); map.put("msg","系统异常"); map.put("errMsg",e.getMessage()); } Iterator<String> iter = multiRequest.getFileNames(); //迭代文件,存放到某一路径里 while (iter.hasNext()) { //取得上传文件 MultipartFile file = multiRequest.getFile(iter.next()); if (null != file) { try { //判断file不能为空 if(file != null){ //将文件传入工具类上传文件,返回的是成功上传文件的路径 String imgPath = QiniuUtils.uploadImg2QiNiu(file); map.put("success",true); map.put("imgPath",imgPath); }else{ map.put("success",false); map.put("msg","上传图片失败!"); } }catch (Exception e){ e.printStackTrace(); map.put("success",false); map.put("msg","系统异常"); map.put("errMsg",e.getMessage()); } } } return map; }下面是前台页面
<!-- 模态框(Modal) --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> × </button> </div> <div class="modal-body" > <form id="imgForm"> <div class="row"> <div class="form-group col-md-4"> <input type="hidden" name="id" id="id"/> <label class="control-label">类型:</label> <select id="updataMerge" name="type" class="commmunityselect" > <option value="-1" selected="selected">全部</option> <option value="1">资产负债表</option> <%-- <option value="2">现金流量表</option>--%> <option value="2">利润表</option> <option value="3">大事记</option> </select> </div> <div class="form-group col-md-4 "> <label class="control-label">日期:</label> <div class="input-daterange input-group" > <input type="text" class="form-control" name="createData" id="upDate"/> </div> </div> </div> <!-- 上传弹出框 --> <div id="uploadDialog" class="upload-dialog"> <ul id="ul_pics"> </ul> <div class="form-group" style="float: left;"> <button class="btn btn-info" id="upImgBt"> <span>上传图片</span> </button> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" οnclick="insertImgInfo()" class="btn btn-primary">确定 </button> <button type="button" class="btn btn-default" data-dismiss="modal" id="close">取消 </button> </div> </div><!-- /.modal-content --> </div><!-- /.modal --> </div>JS脚本
function insertImgInfo() { var sel = $("#updataMerge").val(); var date = $("#upDate").val(); if(sel == -1){ alert("类型不能为空!"); return; }else if(date == null || date == ""){ alert("日期不能为空!"); return; } $.ajax({ url:"./insertEarningsReportInfo", type:"post", data:$("#imgForm").serialize(), dataType:"json", success:function(data){ if(data.success) { window.location.reload(); }else{ console.log("msg",data.msg) console.log("errMsg",data.errMsg) } } }); } var uploader = new plupload.Uploader({ //创建实例的构造方法 runtimes : 'html5,flash,silverlight,html4', browse_button: 'upImgBt', // 上传按钮 url: "../upImgInfo", //远程上传地址 flash_swf_url: '${pageContext.request.contextPath}/assets/plugins/plupload/Moxie.swf', //flash文件地址 silverlight_xap_url: '${pageContext.request.contextPath}/assets/plugins/plupload/Moxie.xap', //silverlight文件地址 filters: { max_file_size: '500kb', //最大上传文件大小(格式100b, 10kb, 10mb, 1gb) prevent_duplicates: true, //不允许选取重复文件 mime_types: [ //允许文件上传类型 {title: "Image files", extensions: "jpg,png,gif"} ] }, file_data_name:'file', unique_names:true, multi_selection: true, //true:ctrl多文件上传, false 单文件上传 init: { FilesAdded: function(up, files) { //文件上传前 var reader = new FileReader(); reader.readAsDataURL(files[0].getNative()); reader.onload = (function (e) { var image = new Image(); image.src = e.target.result; image.onload = function () { if (this.width <= 375) { var li = ''; plupload.each(files, function(file) { //遍历文件 li += "<li id='" + file['id'] + "'><div class='progress'><span class='bar'></span><span class='percent'>上传中 0%</span></div></li>"; }); $("#ul_pics").append(li); uploader.start(); } else { alert("请选择尺寸小于或者等于375的图片!"); } }; }); }, UploadProgress: function(up, file) { //上传中,显示进度条 var percent = file.percent; $("#" + file.id).find('.bar').css({"width": percent + "%"}); $("#" + file.id).find(".percent").text("上传中 "+percent + "%"); }, FileUploaded: function(up, file, info) { //文件上传成功的时候触发 var data = eval("(" + info.response + ")"); $("#" + file.id).html("<img src='" + data.imgPath + "' width='300px' height='300px' /><i οnclick='delimg(this)'>x</i><input type='hidden' name='url' value='"+ data.imgPath +"'>"); }, Error: function(up, err) { //上传出错的时候触发 console.log("err",err); } } }); uploader.init(); function delimg(o){ var src = $(o).prev().attr("src"); $(o).parent().remove(); /* $.post("upimgs.php?get=delimg&imgurl="+src,function(data){ if(data==1){ $(o).parent().remove(); } })*/ } //模态窗口 $('#insertBt').click(function () { $("#myModal1").modal("show"); //显示模态框 $("#myModal").modal({ backdrop: "static", keyboard: false }); }); $(".close").click(function () { window.location.reload(); }) $("#close").click(function () { window.location.reload(); }) //模态修改时间 $('#upDate').datepicker({ language: "zh-CN", autoclose: true, format: 'yyyy-mm', maxDate: "+1D", startView: 'months', //开始视图层,为月视图层 maxViewMode:'years', //最大视图层,为年视图层 minViewMode:'months', //最小视图层,为月视图层 }); //语言样式设置 var i18nZH = { "sProcessing": "处理中...", "sLengthMenu": "显示 _MENU_ 项结果", "sZeroRecords": "没有匹配结果", "sInfo": "显示第 _START_ 至 _END_ 项结果,共 _TOTAL_ 项", "sInfoEmpty": "显示第 0 至 0 项结果,共 0 项", "sInfoFiltered": "(由 _MAX_ 项结果过滤)", "sInfoPostFix": "", "sSearch": "搜索:", "sUrl": "", "sEmptyTable": "表中数据为空", "sLoadingRecords": "载入中...", "sInfoThousands": ",", "oPaginate": { "sFirst": "首页", "sPrevious": "上页", "sNext": "下页", "sLast": "末页" }, "oAria": { "sSortAscending": ": 以升序排列此列", "sSortDescending": ": 以降序排列此列" } }; //页面加载调用查询 $(function () { moment.locale('zh-cn'); //后台调用接口 $('#datatable').DataTable({ dom: "lrtip", language: i18nZH, responsive: !0, "lengthChange": true,//开启显示条数 "lengthMenu": [ 15, 50, 75, 100 ], "ordering": false,//禁止排序 "deferRender": true, "processing": true, "serverSide": true, "scrollX": true, "autoWidth": false, "destroy": true, "ajax": { "url":"../queryImgInfo", "type": "POST", "async" : true, "data": function (d) { //删除多余请求参数 for(var key in d){ if(key.indexOf("columns")==0||key.indexOf("order")==0||key.indexOf("search")==0){ //以columns开头的参数删除 delete d[key]; } } var searchParams = {"type":$('#merge').val(),"createData":$('#dpd1').val(), "pageSize":d.length, "currentPage":parseInt(d.start/d.length)+parseInt(1)}; //附加查询参数 if (searchParams) { $.extend(d, searchParams); //给d扩展参数 } }, "dataType": "json", "dataFilter": function (json) {//json是服务器端返回的数据 json = JSON.parse(json); if(json.success){ console.log("data",json); var returnData = {}; returnData.recordsTotal = json.total;//返回数据全部记录 returnData.recordsFiltered = json.total;//后台不实现过滤功能,每次查询均视作全部结果 returnData.data = json.data;//返回的数据列表 return JSON.stringify(returnData);//这几个参数都是datatable需要的,必须要 }else{ console.log("errInfo",json.errInfo); } } }, /*给数据添加列*/ columns: [ { sTitle: '序号', data: null, className: 'text-center whiteSpace', render:function(data,type,row,meta) { return meta.row + 1 + meta.settings._iDisplayStart; } }, {data: 'createData'}, {data: 'type', "render" : function(data, type, full, meta) { if(data==1){//类型 1.资产负债表 2.利润表 3. 大事记 data ="资产负债表"; }else if(data == 2){ data ="利润表"; }else if(data == 3){ data ="大事记"; }/*else if(data == 4){ data ="大事记"; }*/ return data; } }, {data: 'updateTime', "render" : function(data, type, full, meta) { //时间格式化 return moment(data).format("YYYY-MM-DD HH:mm:ss"); } }, {data: 'upname'}, ], "columnDefs" : [ { // 定义操作列,######以下是重点######## "targets" : 5,//操作按钮目标列 "data" : null, "render" : function(data, type,row) { var id = '"' + row.id + '"'; var html =""; html += "<a href='javascript:void(0);' οnclick='queryThisRowInfoByid("+id+")'> 编辑</a>" html += " 丨" html += "<a href='javascript:void(0);' οnclick='deleteThisRowPapser("+ id+ ")'> 删除</a>" return html; } } ], }); }) //回显信息 function queryThisRowInfoByid(id) { $.ajax({ url:"./queryThisRowInfoById", type:"post", data:{"id":id}, dataType:"json", success:function (data) { if(data.success){ $("#myModal1").modal("show"); //显示模态框 $("#myModal").modal({ backdrop: "static", keyboard: false }); //id updataMerge upDate ul_pics $("#id").val(data.earningsReport.id); $("#updataMerge").val(data.earningsReport.type); $("#upDate").val(data.earningsReport.createData); var li = ""; var sid = ""; var index = ""; var liArr = new Array(); //定义一数组 var imgUrl = data.earningsReport.url; liArr = imgUrl.split(","); //字符分割 for (i = 0;i < liArr.length ;i++ ) { index = liArr[i]; index = index.lastIndexOf("/"); sid = liArr[i].substr(index +1); li += "<li id='" + sid + "'></li>"; } $("#ul_pics").append(li); $('li').each(function(){ for (i = 0;i < liArr.length ;i++ ) { index = liArr[i]; index = index.lastIndexOf("/"); sid = liArr[i].substr(index +1); if($(this).attr('id') == sid){ $(this).html("<img src='" + liArr[i] + "' width='300px' height='300px' /><i οnclick='delimg(this)'>x</i><input type='hidden' name='url' value='"+ liArr[i] +"'>"); } } }); }else{ } } }) }
//删除信息 function deleteThisRowPapser(id) { $("#deleteOneModal").modal('show'); console.log("id",id) /** * 点击确认删除按钮 */ $(document).delegate('#delSubmit','click',function(){ $('#deleteOneModal').modal('hide'); $.ajax({ url:"./deleteImgInfoById", type:"post", data:{"id":id}, dataType:"json", success:function(data){ if(data.success) { window.location.reload(); } else { console.log("msg",data.msg) console.log("errMsg",data.errMsg) } } }); }); } //搜索 function getData() { var table = $("#datatable").DataTable(); // table.destroy(); /* var merge=$('#merge').val();*/ table.ajax.reload(); table.columns.adjust(); } $.fn.dataTable.ext.errMode = 'none'; //不显示任何错误信息 //以下为发生错误时的事件处理,如不处理,可不管。 $('#datatable').on( 'error.dt', function ( e, settings, techNote, message ){ //这里可以接管错误处理,也可以不做任何处理 console.log( 'An error has been reported by DataTables: ', message ); }).DataTable();