• java 图片上传方法


     这个上传图片比较简单,将图片上传到程序里的特定文件夹中,读取时直接读取。

    jsp页面

    <%@page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
    <html>
        <head>
            <title>上传图片</title>
            <%@ include file="../commons/jsp/include.jsp"%>
            <script type="text/javascript" src="<c:url value="upLoadImgIndex.js"></c:url>"></script>
        </head>
    <style>
        #box{
          100%;
          margin-top:20px;
        }
        #imgshow{
           300px;
          height:279.1px;
          line-height:279.1px;
          text-align:center;
          font-size:20px;
          color:#DDD;
          border:2px solid #858585;
          margin:0 auto;
          display: block;
        }
        #pox{
            text-align:center;
            padding-top:50px;
            padding-bottom:50px;
        }
        #pox > div{
          margin:0 auto;
          display:inline;
        }
        input[id=filed]{
            display:none;
        }
     </style>
        <body>
          <div id="box">
            <img id="imgshow" src="" alt="图片预览"/>
          </div>
          <div id="pox">
                  <div>
                    <input onmouseover="javascript:this.className='ButtonOver'" onmouseout="javascript:this.className='Button'" value=" 选择流程图  " class="Button" type="button" onclick="$('input[id=filed]').click();"/>
                    <input id="writeImg_Mz" onmouseover="javascript:this.className='ButtonOver'" onmouseout="javascript:this.className='Button'" value=" 确认并上传 门诊流程图 " class="Button" type="button"/>
                    <input id="writeImg_Zy" onmouseover="javascript:this.className='ButtonOver'" onmouseout="javascript:this.className='Button'" value=" 确认并上传 住院流程图 " class="Button" type="button"/>
                    <input id="filed" type="file" accept="image/*"/>
               </div>
          </div>
        </body>
    </html>

    js方法

    var imgBase64 = "",file,fileSize,postfix,reader,params;
    $(function(){
         //在input file内容改变的时候触发事件
        //图片预览方法
            $("#filed").change(function(){
            //获取input file的files文件数组;
            //$('#filed')获取的是jQuery对象,.get(0)转为原生对象;
            //这边默认只能选一个,但是存放形式仍然是数组,所以取第一个元素使用[0];
              file = $("#filed").get(0).files[0];
              fileSize = Number((file.size/1024).toFixed(2));
              postfix = file.name.substring(file.name.length-3,file.name.length);
              if(fileSize > 60){
                  alert("图片不能大于60KB");
              }else if(postfix != "jpg"){
                  alert("请选择文件类型为.jpg的图片");
              }else{
                //创建用来读取此文件的对象
                 reader = new FileReader();
                //使用该对象读取file文件
                 reader.readAsDataURL(file);
                //读取文件成功后执行的方法函数
                 reader.onload=function(e){
                //读取成功后返回的一个参数e,整个的一个进度事件
                 imgBase64 = e.target.result;
                //选择所要显示图片的img,要赋值给img的src就是e中target下result里面
                //的base64编码格式的地址
                    $("#imgshow").get(0).src = e.target.result;
                 }
              }
            });
            $("#writeImg_Mz").click(function(){
                sendBase64Img(1);
            });
            $("#writeImg_Zy").click(function(){
                sendBase64Img(2);
            });
    })
    /**
     * @param typeImg 1:门诊,2:住院
     */
    function sendBase64Img(typeImg){
        if(imgBase64 == "" || imgBase64 == null){
            if(typeImg == "1"){
                alert("请选择门诊流程图!");
            }else if(typeImg == "2"){
                alert("请选择住院流程图!");
            }else{
                alert("请选择流程图!");
            }
        }else{
            params = {"imgBase64":imgBase64,"typeImg":typeImg}
            $.ajax({
                type : "POST",
                ASYNC:true,
                url:baseUrl + "/hospdoc/writeImg.do",
                data:params,
                dataType : "json",
                success : function(successData){
                    if(successData.isSuccess == "yes"){
                        alert("上传更新成功!");
                    }else{
                        alert("上传更新失败!");
                    }
                },
                error : function(data) {
                    alert("上传更新失败!");
                }
            });
        }
        
    }

    java方法

        /**
         * 点击上传照片功能
         */
        public String writeImg(){
            try{
                HttpServletRequest request = WebUtils.getRequest();
                //request.getSession().getServletContext() 获取的是Servlet容器对象,相当于tomcat容器了。
                //getRealPath("/") 获取实际路径,“/”指代项目根目录,所以代码返回的是项目在容器中的实际发布运行的根路径
                String absPath=request.getSession().getServletContext().getRealPath("/");
                //request.getContextPath()应该是得到项目的名字,如果项目为根目录,则得到一个"",即空的字条串。
                String projectName = request.getContextPath();
                //java replaceAll() 方法要用 4 个反斜杠,表示一个反斜杠
                absPath = absPath.replaceAll("\\","//");
                absPath = absPath+"znfz//images//jzlcImg//";
                String base64String = request.getParameter("imgBase64");
                String typeImg = request.getParameter("typeImg");
                base64String = base64String.substring(23, base64String.length());
                base64String = base64String.replaceAll(" ","+");
                String toImagePath = "";
                /*File file=new File(wappPath+"xyhImg"); 
                //如果文件夹不存在则创建    
                if (!file.exists()  && !file.isDirectory()){       
                    file.mkdir();    
                }*/
                if(typeImg.equals("1") || typeImg == "1"){
                    toImagePath = absPath+"mzlcImg.jpg";
                }else if(typeImg.equals("2") || typeImg == "2"){
                    toImagePath = absPath+"zylcImg.jpg";
                }
                String imageType = "jpg";
                base64StringToImage(base64String,toImagePath,imageType);
            }catch(Exception e){
                model.put("isSuccess", "no");
                e.printStackTrace();
            }
            model.put("isSuccess", "yes");
            return getResult();
        }
        public static boolean base64StringToImage(String base64String,String toImagePath,String imageType) {
              try {
               BASE64Decoder decoder = new sun.misc.BASE64Decoder();
               byte[] bytes1 = decoder.decodeBuffer(base64String);
    
               ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
               RenderedImage bi1 = ImageIO.read(bais);
               File w2 = new File(toImagePath);// 可以是jpg,png,gif格式
               if(!w2.exists()){
                w2.createNewFile();
               }
               return ImageIO.write(bi1, imageType, w2);// 不管输出什么格式图片,此处不需改动
              } catch (Exception e) {
               e.printStackTrace();
               return false;
              }
        } 

    读取图片页面

    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    <html>
    <head>
    <title>住院流程图</title>
    <%@page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
    <%@ include file="../../commons/jsp/mobileIncludeNew.jsp"%>
    <script type="text/javascript" src="<c:url value="../code/initFontSize.js"></c:url>"></script>
    </head>
    <body data-role="page">
        <img class="jzlcImg" src="../images/jzlcImg/zylcImg.jpg"/>
    </body>
    </html>
  • 相关阅读:
    最全的 Twitter Bootstrap 开发资源清单
    jQuery布局插件UI Layout简介及使用方法
    SQLcode错误代码汇总和sqlstate=37000的解决方案
    JQUERY插件学习之jQuery UI
    如何判断/检查一个集合(List<string>)中是否有重复的元素
    反射原理及简介
    C# 获取文件夹下的所有文件的文件名
    委托编程指南
    模块封装与程序集
    Redis Lock
  • 原文地址:https://www.cnblogs.com/liujie-e2/p/9185267.html
Copyright © 2020-2023  润新知