1.首先为html代码以及js代码
<div id="uploadDiv" style="display:none;"> <!-- The fileinput-button span is used to style the file input field as button --> <span class="btn btn-success fileinput-button"> <i class="glyphicon glyphicon-plus"></i> <span>文件选择</span> <!-- The file input field used as target for the file upload widget --> <input id="fileupload" type="file" name="file" > </span> <button id="uploadBtn" class="btn btn-primary disabled" >确认上传</button> <br> <!-- The global progress bar --> <div id="progress" class="progress"> <div class="progress-bar progress-bar-success"></div> </div> <!-- The container for the uploaded files --> <div id="msgDiv" class="files"></div> </div>
$("#uploadBtn").click(function(){ var dialog = $("#uploadDiv").clone().dialog({ title: "附件上传", width : '75%', height : 500, modal : true }); $('#fileupload', dialog).fileupload({ dataType: 'json', progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress .progress-bar', dialog).css( 'width', progress + '%' ).html(progress + '%'); $("#msgDiv", dialog).html("处理中……"); }, add: function (e, data) { data.url = "ra/suspiciousCase/uploadTotal"; data.submit(); $("#uploadBtn", dialog).off('click').on('click', function () { var id = getUrlParam('id'); data.url = "ra/suspiciousCase/upload?id="+id; data.submit(); setTimeout(function(){handleUploadTable();}, 3000);//延迟执行刷新 }); }, done: function (e, data) { var isTotal = data.url.indexOf("uploadTotal") > -1; var tip = isTotal ? "解析成功,请点击“确认上传”" : "上传"; var result = data.result; var msg = "<b>" + tip + "</b>" var bar = $('#progress .progress-bar'); bar.removeClass("progress-bar-warning progress-bar-success"); if(!result.success){ msg = "<b>" + tip + "失败:</b>"+result.error; bar.addClass("progress-bar-warning"); $("#uploadBtn", dialog).addClass("disabled"); }else{ bar.addClass("progress-bar-success"); msg = "<b>" + tip + "成功:</b>"; if(isTotal){ $("#uploadBtn", dialog).removeClass("disabled"); } } if(result.totalInfo){ msg += "<br>"; msg += "<b>提示信息:</b>" + result.totalInfo; } msg += "<br><b>文件名称:</b>" + data.files[0].name; $("#msgDiv", dialog).html(msg); } }) })
再来是后台代码
@Path("/upload") @POST @NoCache @Consumes("multipart/form-data") public ExtJSResponse upload(@Context HttpServletRequest request) { ExtJSResponse resp = new ExtJSResponse(true); final String id = request.getParameter("id"); final AmlSuspectcaseAttach attach = new AmlSuspectcaseAttach(); boolean isMultipart= ServletFileUpload.isMultipartContent(request); if(isMultipart){ //构造一个文件上传处理对象 FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); @SuppressWarnings("rawtypes") Iterator items; try{ checkPermission(Permissions.AML_SUSPECT_CASE); //解析表单中提交的所有文件内容 items = upload.parseRequest(request).iterator(); while(items.hasNext()){ FileItem item = (FileItem) items.next(); if(!item.isFormField()){ //取出上传文件的文件名称 String name = item.getName(); logger.info("上传文件的大小为:[{}]",item.getSize()); //取得上传文件以后的存储路径 final String suffix = name.substring(name.lastIndexOf('.') + 1, name.length()); int fsize = fileSize*1024*1024; if(fileSuffix.contains(suffix)){ if(item.getSize() < fsize){ Long attachId = null; if(!StringUtils.isEmpty(name)){ attach.setName(name); } if(!StringUtils.isEmpty(id)){ attach.setCaseid(Long.parseLong(id)); attachId = suspectCase.insertAttch(attach); System.out.println("attach:"+attachId); } if(resp.isSuccess()){ //上传文件以后的存储路径 logger.info("上传文件:[{}]",attachId+"."+suffix); String Path= amlPath + File.separatorChar + attachId; File file =new File(amlPath); //如果文件夹不存在则创建 if (!file.exists() && !file.isDirectory()) { file.mkdir(); } //上传文件 logger.info("上传文件的路径为:[{}]",Path); File uploaderFile = new File(Path); item.write(uploaderFile); } }else{ logger.info("上传文件大小不能超过2M"); resp.setSuccess(false); resp.setErrorMsg("上传文件大小不能超过2M"); } }else{ logger.info("文件格式不正确,请选择doc、docx、xls、xlsx、png、gif、jpg、jpeg、bmp后缀文件!"); resp.setSuccess(false); resp.setErrorMsg("文件格式不正确,请选择doc、docx、xls、xlsx、png、gif、jpg、jpeg、bmp后缀文件!"); } } } }catch(Exception e){ e.printStackTrace(); resp.setSuccess(false); resp.setErrorMsg("文件上传失败"); } } return resp; } @Path("/uploadTotal") @POST @NoCache @Consumes("multipart/form-data") public ExtJSResponse uploadTotal(@Context HttpServletRequest request) { ExtJSResponse resp = new ExtJSResponse(true); @SuppressWarnings("unused") InputStream instream = null; try { checkPermission(Permissions.AML_SUSPECT_CASE); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator fileIterator = upload.getItemIterator(request); while (fileIterator.hasNext()) { FileItemStream item = fileIterator.next(); if ("file".equals(item.getFieldName())){ instream = item.openStream(); break; } } StringBuilder total = new StringBuilder(); resp.put("totalInfo", total); } catch (Exception e) { getLogger().warn(e.getMessage(), e); resp.setSuccess(false); resp.setErrorMsg(e.getLocalizedMessage()); } return resp; }
其中uploadTotal方法是在文件上传之前先对文件进行解析,下面贴上我的上传效果图,我这里是用的frame弹窗
解析完再点击确认上传之后就完成了。