手機端上傳圖片及java後臺接收和ajaxForm提交

有不少微信開發的項目在手機端須要傳圖片,可是又不想調用微信的上傳圖片接口,因而採起了以下作法:javascript

使用ajaxForm提交文件所需js:jquery.form.jscss

頁面代碼:html

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@include file="/context/mytags.jsp"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<title>頁面標題</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<meta name="description" content="Write an awesome description for your new site here. You can edit this line in _config.yml. It will appear in your document head meta (for Google search results) and in your feed.xml site description.
">
<link rel="stylesheet" href="${contextPath}/plug-in/distribution/lib/weui.min.css">
<link rel="stylesheet" href="${contextPath}/plug-in/distribution/css/jquery-weui.css">
<link rel="stylesheet" href="${contextPath}/plug-in/distribution/css/style.css">
<style type="text/css">
.file {
    position: relative;
    display: inline-block;
    background: #D0EEFF;
    border: 1px solid #99D3F5;
    border-radius: 4px;
    padding: 4px 12px;
    overflow: hidden;
    color: #1E88C7;
    text-decoration: none;
    text-indent: 0;
    line-height: 20px;
}
.file input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
}
.file:hover {
    background: #AADFFD;
    border-color: #78C3F3;
    color: #004974;
    text-decoration: none;
}
</style>
<script>
$(document).ready(function(){
});
</script>
</head>
<body ontouchstart onload="addressList();">
<!--主體-->
<header class="wy-header">
  <a href="#" onClick="javascript :history.back(-1);"><div class="wy-header-icon-back"><span></span></div></a>
  <div class="wy-header-title">資料上傳</div>
</header>
<div class="weui-content">
    <form id="imageForm" name="imageForm" action="${webRoot}/agentPicController.do?doAdd" method="post" enctype="multipart/form-data">    
        <input type="hidden" name="agentId" id="agentId" value="${agent.id}" />
        <div style="width:100%;height:80px;">
               <span style="float: left;">&nbsp;&nbsp;&nbsp;<font size="4" color="blue">個人收款碼:</font></span><br/>
            <input style="height:30px;" class="file" type="file" name="agentCollectionCodes" id="agentCollectionCodes"  accept="image/*"/>
            <div id="agentCollectionCodess" align="center"></div>
        </div>
        <div style="width:100%;height:80px;">
            <span style="float: left;">&nbsp;&nbsp;&nbsp;<font size="4" color="blue">個人身份證:</font></span><br/>
            <input style="height:30px;" type="file" class="file" name="agentIdentitys" id="agentIdentitys" accept="image/*"/>
            <div id="agentIdentityss" align="center"></div>
        </div>
        
        <div class="weui-btn-area"><input id="buttonAdd"  class="weui-btn weui-btn_primary" type="button" value="提交圖片"/></div>
        
    </form>
</div>

<jsp:include page="loading.jsp"></jsp:include>
<jsp:include page="footer.jsp"></jsp:include>
<jsp:include page="shareinfo.jsp"></jsp:include>
<script src="${contextPath}/plug-in/distribution/lib/jquery-2.1.4.js"></script> 
<script src="${contextPath}/plug-in/distribution/lib/fastclick.js"></script> 
<script type="text/javascript" src="${contextPath}/plug-in/distribution/js/jquery.Spinner.js"></script>
<script type="text/javascript" src="${contextPath}/plug-in/distribution/js/jquery.form.js"></script>

<script>
  var AllImgExt=".jpg|.jpeg|.gif|.bmp|.png|"//所有圖片格式類型 
  
  $(function() {
    FastClick.attach(document.body);
  });
  $("#buttonAdd").click(function() { 
      //身份證
      var agentIdentitys = $("#agentIdentitys").val();
      if (agentIdentitys==null||agentIdentitys=="") {
         $.alert("請上傳身份證圖片","舒適提示");
         return false; 
      }else{
          //若是圖片文件,則進行圖片信息處理 
          var FileExt=agentIdentitys.substr(agentIdentitys.lastIndexOf(".")).toLowerCase();
          if(AllImgExt.indexOf(FileExt+"|")==-1){ 
              $.alert("該文件類型不容許上傳。請上傳"+AllImgExt+"類型的文件,\n當前文件類型爲"+FileExt,"舒適提示"); 
              return false; 
          } 
      }
      //收款碼
      var agentCollectionCodes = $("#agentCollectionCodes").val();
      if (agentCollectionCodes==null||agentCollectionCodes=="") {
         $.alert("請上傳收款碼圖片","舒適提示");
         return false; 
      }else{
          //若是圖片文件,則進行圖片信息處理 
          var FileExt=agentCollectionCodes.substr(agentCollectionCodes.lastIndexOf(".")).toLowerCase();
          if(AllImgExt.indexOf(FileExt+"|")==-1){ 
              $.alert("該文件類型不容許上傳。請上傳"+AllImgExt+"類型的文件,\n當前文件類型爲"+FileExt,"舒適提示"); 
              return false; 
          } 
      }
      $("#loading").show();
      var form = $("#imageForm");
      var options  = {  
          url:'${webRoot}/agentPicController.do?doAdd',  
          type:'post',  
          data:$('#imageForm').serialize(),
          success:function(data)  
          {   
                window.location.href="${webRoot}/mpweixin/uploadImages.do";
              //$("#loading").hide();    
          }  
      };  
      form.ajaxSubmit(options);
  });
</script>
<script src="${contextPath}/plug-in/distribution/js/jquery-weui.js"></script>
</body>
</html>

java代碼:java

    /**
     * 添加圖片
     * 
     * @param ids
     * @return
     * @throws FileUploadException 
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(AgentPicEntity agentPic, HttpServletRequest request) throws Exception {
        String message = null;
        AgentPicEntity agentpic = systemService.findUniqueByProperty(AgentPicEntity.class, "agentId", agentPic.getAgentId());
        if (agentpic==null) {
            agentpic = new AgentPicEntity();
        }
        agentpic.setAgentId(agentPic.getAgentId());
        //身份證
        String agentIdentity = "agentIdentity";
        //付款碼
        String agentCollectionCode = "agentCollectionCode";
        AjaxJson j = new AjaxJson();
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; 
        //解析request,將結果放置在list中
        Map<String, List<MultipartFile>> fileMap = multiRequest.getMultiFileMap();
        // 獲取實體類的全部屬性,返回Field數組
        Field[] field = agentpic.getClass().getDeclaredFields();
        // 遍歷全部屬性
        for (int i = 0; i < field.length; i++) {
            // 獲取屬性的名字
            String name = field[i].getName();
            //身份證或付款碼
            if (agentIdentity.equals(name)||agentCollectionCode.equals(name)) {
                List<MultipartFile> files = fileMap.get(name+"s");
                MultipartFile file = files.get(0);
                if (!file.isEmpty()) {
                    // 文件保存路徑  
                    String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/agentpic/"+ file.getOriginalFilename();  
                    // 轉存文件  
                    file.transferTo(new File(filePath)); 
                    
                    // 將屬性的首字符大寫,方便構造get,set方法
                    name = name.substring(0, 1).toUpperCase() + name.substring(1);
                    // 獲取屬性的類型
                    String type = field[i].getGenericType().toString();
                    if (type.equals("class java.lang.String")) {
                        //拼裝setter方法
                        Method set = agentpic.getClass().getMethod("set"+name,String.class);
                        //調用setter方法
                        set.invoke(agentpic,"upload/agentpic/"+ file.getOriginalFilename());
                    }
                }
            }
        }
        message = "圖片添加成功";
        try{
            agentPicService.saveOrUpdate(agentpic);
        }catch(Exception e){
            e.printStackTrace();
            message = "圖片添加失敗";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }
相關文章
相關標籤/搜索