miniui实现多附件上传

最近项目要开发一个多附件上传问题管理的需求,我们项目前端用的是miniui +jquery ,于是去miniui官网看有没有多附件上传相关的组件,发现一个MultiUpload Window的表单控件,看了下源代码基本上可以实现我想要的功能,下面贴一下我几天的研究成果。

MultiUpload 是基于swfupload封装好的一个多附件上传的控件

minui多附件控件

请求页面需要引入multiupload.css、swfupload.js、swfupload.swf、multiupload.js、cancel.gif,可以去官网下载源代码拷贝到自己的项目中来

“uploadurl”要最好使用绝对路径,相对路径“/**/”可能出现请求404的问题

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="/resources/context/jspBase.jsp"%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<title>Insert title here</title>
<%@ include file="/resources/context/headResource.jsp"%>
<link href="resources/plugins/multiUpload/multiupload.css" rel="stylesheet" type="text/css" />
<style>

html, body {
  overflow: hidden; /* overflow|overflow-x|overflow-y : visible|hidden|scroll|auto */
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0;
}

</style>
</head>
<body>

  <script src="${basePath}resources/plugins/multiUpload/swfupload.js" type="text/javascript"></script>
  <script src="${basePath}resources/plugins/multiUpload/multiupload.js" type="text/javascript"></script>
 <!--   <script src="${basePath}/resources/plugins/multiUpload/boot.js" type="text/javascript"></script>-->

  <div class="mini-panel" style="width: 100%; height: 100%" showfooter="true" bodystyle="padding:0" borderStyle="border:0"
        showheader="false">

        <div id="multiupload1" class="uc-multiupload" style="width: 100%; height: 100%" enctype="multipart/form-data" 
            flashurl="${basePath}resources/plugins/multiUpload/swfupload.swf"
            uploadurl="${basePath}PmIssueController/upload" _autoupload="true" borderstyle="border:0" >
        </div>

        <div property="footer" style="padding:8px; text-align: center">
            <a class="mini-button" onclick="onOk" style="width: 80px" iconcls="icon-ok">确定</a>
            <a class="mini-button" onclick="onCancel" style="width: 80px; margin-left: 50px"
                iconcls="icon-cancel">取消</a>
        </div>

    </div>
    <script type="text/javascript">
    mini.parse();
    var grid = mini.get("multiupload1");    
    function saveData() {
        CloseWindow("ok");
    }
    function CloseWindow(action) {
        if (window.CloseOwnerWindow) return window.CloseOwnerWindow(action);
        else window.close();
    }
    function onOk(e) {
        saveData();
    }
    function onCancel(e) {        
        CloseWindow("cancel");
   }

   function SetData(params) {

       grid.setPostParam(params);
   }

   function GetData() {
        var rows = grid.findRows(function (row) {
            if (row.status == 1) {
                return true;
            }
        })
        return rows;
    }
    </script>
  <%@ include file="/resources/context/lazyResource.jsp"%>
</body>
</html>

controller部分:
注意: 多个文件上传并不是一次性上传多个文件而是一个上传完成后再上传另一个,有几个文件就会请求几次。

@ResponseBody
  @RequestMapping("upload")
  public Map<String, Object> upload(HttpServletRequest request,HttpServletResponse response) throws Exception{
  //接收前台传过来的参数
   String number = request.getParameter("number");
   String attachmentType = request.getParameter("attachmentType");
   String projectName = request.getParameter("projectName");
   Map<String, Object> modelMap = new HashMap<String, Object>();   
    try {
    //处理上传文件方法getFilesFromRequest
      List<FileEntity> list = FileUtils.getFilesFromRequest(request);
      if (list == null || list.size() == 0) {
        throw new Exception("上传失败");
      }
      for (FileEntity entity : list) {
//        response.getWriter().write(entity.getFileName());
        newIssueService.fileUplode(number, attachmentType, entity);

        IssueAttachment issueAttachment = new IssueAttachment();
        issueAttachment.setIssueNumber(number);
        issueAttachment.setProjectName(projectName);
        issueAttachment.setFileName(entity.getFileName());
        issueAttachment.setFileType(entity.getFileType());
        if(attachmentType.equals("directCouseAttachment")){
          //"1"表示上传的是该种类的附件
          issueAttachment.setDirectCouseAttachment("1");
        }else if(attachmentType.equals("primaryCouseAttachment")){
          issueAttachment.setPrimaryCouseAttachment("1");
        }
        else if(attachmentType.equals("designImprovementAttachment")){        
          issueAttachment.setDesignImprovementAttachment("1");
        }else if(attachmentType.equals("processImproveAttachment")){
          issueAttachment.setProcessImproveAttachment("1");
        }else if(attachmentType.equals("improvementResultAttachment")){
          issueAttachment.setImprovementResultAttachment("1");        
        }else if(attachmentType.equals("negativeEffectAttachment")){
          issueAttachment.setNegativeEffectAttachment("1");
        }else if(attachmentType.equals("designRuleAttachment")){
          issueAttachment.setDesignRuleAttachment("1");
        }else if(attachmentType.equals("ctqProjectManageAttachment")){
          issueAttachment.setCtqProjectManageAttachment("1");
        }
 //写入数据库上传文件的相关信息          issueAttachmentService.create(issueAttachment,attachmentType);
      } 

      modelMap.put("success", "true");      
    } catch (Exception e) {
      modelMap.put("success", "false");
    }
    return modelMap;
  }
/**
   * 从request中提取上传的文件列表
   * 
   * @param request HttpServletRequest
   */
  public static List<FileEntity> getFilesFromRequest(HttpServletRequest request) {
    List<FileEntity> files = new ArrayList<FileEntity>();
    //多附件上传需要用到的MultipartHttpServletRequest,可以度娘一下它的用法
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
    try {
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
        InputStream inputstream = entity.getValue().getInputStream();
        if (!(inputstream.markSupported())) {
          inputstream = new PushbackInputStream(inputstream, 8);
        }

        String fileName = entity.getValue().getOriginalFilename();
        String prefix =
            fileName.lastIndexOf(".") >= 1 ? fileName.substring(fileName.lastIndexOf(".") + 1)
                : null;
        FileEntity file = new FileEntity();
        file.setInputStream(inputstream);
        file.setFileType(prefix);
        file.setFileName(fileName);
        files.add(file);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return files;
  }
/**
   * issue附件上传客户端到服务器
   * @throws Exception 
   */
  public void fileUplode(String number,String attachmentType,FileEntity entity)
          throws Exception {
    //number为流水编号、attachmentType为上传附件的类型,entity文件实体类
      OutputStream os = null;
      try {
          File outfile = creatTempFile(number,attachmentType);
          File toFile = new File(outfile, entity.getFileName());
          // 创建一个输出流
          os = new FileOutputStream(toFile);
          // 设置缓存
          byte[] buffer = new byte[1024];
          int length = 0;
          // 读取myFile文件输出到toFile文件中
          while ((length = entity.getInputStream().read(buffer)) > 0) {
              os.write(buffer, 0, length);
          }

      } catch (Exception ex) {
          String falsemes = "";
          if (ex.getCause() != null) {
              falsemes = ex.getCause().getMessage();
          }
          throw new Exception(ex.getMessage() + falsemes);
      } finally {
          try {
              if (os != null) {
                  os.close();
              }
          } catch (IOException e) {
              throw new Exception(e.getMessage());
          }
      }

  }

上传面板页面

function openW(e) {
          var number = $("#issueForm")[0].issueNumber.value;
          var projectName = $("#issueForm")[0].projectName.value;
          mini.open({
              title: "上传面板",
              //url: "src/uploadwindow.html",
              url: "PmIssueController/multiupload",
              width: 600,
              height: 350,
              allowResize: false,
              onload: function () {
                  var iframe = this.getIFrameEl();
                  var data = {number: number ,attachmentType: e ,projectName: projectName};  //模拟传递上传参数
                  iframe.contentWindow.SetData(data);
              },
              ondestroy: function (action) {
                  if (action == "ok") {
                      var iframe = this.getIFrameEl();

                      var data = iframe.contentWindow.GetData();
                      data = mini.clone(data);

                      var json = mini.encode(data);
           //           alert("已完成上传数据:\n" + json);
                  }
              }
          })
      }

代码虽然不多,但是遇到的坑还是很多的^~^
希望小弟的一点经验能给大家提供一些参考或者思路。

猜你喜欢

转载自blog.csdn.net/rixingbeioul46364/article/details/78732388