码迷,mamicode.com
首页 > 移动开发 > 详细

手机端上传图片及java后台接收

时间:2018-01-20 18:57:12      阅读:1890      评论:0      收藏:0      [点我收藏+]

标签:contex   gen   unique   for   include   oct   map   equals   uil   

有很多微信开发的项目在手机端需要传图片,但是又不想调用微信的上传图片接口,于是采取了如下做法:

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

页面代码:

<%@ 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代码:

    /**
     * 添加图片
     * 
     * @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;
    }

 

手机端上传图片及java后台接收

标签:contex   gen   unique   for   include   oct   map   equals   uil   

原文地址:https://www.cnblogs.com/shuilangyizu/p/8321415.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!