`
annan211
  • 浏览: 445536 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

JEECG 上传头像,图片并切割

阅读更多



 Jcrop  + commons-fieldupload
上传组件上传图片并切割

 

图片上传并完成切割,图片的切割必须在服务器端完成,在客户端是无法进行切割的,至少在目前阶段。

 

1 母页面

registration_purchasers_1.html

 

 

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<metahttp-equiv="X-UA-Compatible"content="IE=EmulateIE7"/>

<metahttp-equiv="Content-Type"content="text/html; charset=utf-8"/>

<head>

<title>参会报名-中国东盟博览会</title>

<script>

    function doForm(){

       if($("#photoNo").val()=="8"){//服务器出错

           alert('对不起,请您按照要求填写表单并上传头像!');

           $("#citySel2").attr("value","");

           $("#citySel").attr("value","");

           $("#photoNo").val("");

           return;

       }else{

           jQuery("#form").submit();

           $("#citySel2").attr("value","");

           $("#citySel").attr("value","");

       }

    }

jQuery(document).ready(function(){

    $("#form").bind("jqv.form.validating", function(event){

       $("#zp_t").html("")

    })

 

    $("#form").bind("jqv.form.result", function(event , errorFound){

       if(errorFound) $("#zp_t").append("表单没有通过验证");

    })

 

    jQuery("#form").validationEngine({

 

    });

    $("input[booth='booth']").change(function(){

       var t = $(this);

       var v = $(this).val();

       $("input[booth='booth']").each(function(){

              $(this).val("");

           });

       t.val(v);

    });

       function openB(){

           //digStr="dialogHeight:100px;dialogWidth:200px;center:yes"

           //var ReturnValue = window.showModalDialog("apply/jQueryImgCrop/index.jsp","",digStr)

       window.showModalDialog("apply/jQueryImgCrop/index.jsp",window,"dialogHeight:300px;dialogWidth:420px;center:yes");

            //window.open("apply/jQueryImgCrop/index.jsp",400,300);

           }

 

           /**检查图片上传类型*/

        function checkImgType(obj){

 

         var imgFile = '';

         //获取图片的全路径

         var imgFilePath = getImgFullPath(obj);

         var endIndex = imgFilePath.lastIndexOf("\\");

         var lastIndex = imgFilePath.length-endIndex-1;

         if (endIndex != -1)

            imgFile= imgFilePath.substr(endIndex+1,lastIndex);

         else

            imgFile = imgFilePath;

 

         var tag = true;

         endIndex = imgFilePath.lastIndexOf(".");

         if (endIndex == -1)

           tag = false;

 

         var ImgName = imgFilePath.substr(endIndex+1,lastIndex);

         ImgName = ImgName.toUpperCase();

 

         if (ImgName !="GIF" && ImgName !="JPG" && ImgName !="PNG" && ImgName !="BMP"){

             tag=false;

         }

         if (!tag) {

             alert("上传图片的文件类型必须为: *.gif,*.jpg,*.png,*.bmp,请重新选择!")

             Upload.clear(obj);

             returnfalse;

         }

              $.ajax({

                     type: "POST",

                     url: $('form1').attr("action"),

                     //url:/ImgUploadServlet,

                     //data: $('form').serialize(),

                     success: function(msg){

                         alert( "registration_purchasers_1: " + msg );

                         window.opener.document.getElementById("ImgPath").src = msg;

                         //window.opener.close();

                            //window.close();

                     }

                  });

      }

 

       function getImgFullPath(obj) {

           if (obj) {

              //ie

              if (window.navigator.userAgent.indexOf("MSIE") >= 1) {

                  obj.select();

                  return document.selection.createRange().text;

              }

              //firefox

              elseif (window.navigator.userAgent.indexOf("Firefox") >= 1) {

                  if (obj.files) {

                      return obj.files.item(0).getAsDataURL();

                  }

                  return obj.value;

              }

              return obj.value;

          }

       }

</script>

</head>

 

<bodyonblur="pageFocus();">

 

            <divclass="cyrzp">

              <divclass="zp_t">

               <tbody>

                     <tr>

                 <td><imgid="ImgPath"src=""style="display:none;"align="middle"onload="getWidthAndHeight(img1);DrawImage2(img1)"height="133"width="99"alt="120x160"></td>

                    </tr>

                      <tr>

                        <tdalign="left"valign="top">

                          <divid="imgdiv"><imgsrc=""id="img"/></div>

                           <!--<div id="avatar_priview"></div>-->

                        </td>

                      </tr>

                  </tbody></table>

              </div>

           <inputtype="text"  id="photoNo"   value=""style="display:none;"/>

           <inputtype="text"  id="photo"   value=""style="display:none;"/>

         <inputtype="hidden"name="fileName"value=""  id="file"  />

              <divclass="zp_m">

               <atype="button"href="javascript:void(0);"onclick="openB()">上传照片</a>

              <!--<a type="button"  class="zp_m" id="preview" onclick="previewCertificatePhoto()">预览照片</a>-->

              </div>

              <divid="liveStatus"style="font-weight:bold;height:20px;"></div>

              <divclass="zp_b">

                <p>照片为申请人的近期正面两寸免冠彩色半身证件照,要求分辨率必须等于或大于240象素¡Á320象素,大小限50K内,格式为"*.jpg"。若上传照片出现问题,建议使用IE7及以上版本的浏览器访问本页,重新上传。</p>

              </div>

            </div>

          </div>

</body>

</html>

 

 

2 弹出的第一层页面

 

Apply/JqueryImgCrop/index.jsp

 

 

 

<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

  <head>

    <basehref="<%=basePath%>">

    <script src="apply/jQueryImgCrop/scripts/clearFile.js" type="text/javascript"></script>

    <script src="apply/jQueryImgCrop/scripts/jquery.min.js"></script>

 

 

    <script type="text/javascript">

       /**检查图片上传类型*/

        function checkImgType(obj){

           //alert("进入checkImgType");

         var imgFile = '';

 

         //获取图片的全路径

         var imgFilePath = getImgFullPath(obj);

        // alert(imgFilePath);

         var endIndex = imgFilePath.lastIndexOf("/");

         var lastIndex = imgFilePath.length-endIndex-1;

         if (endIndex != -1)

            imgFile= imgFilePath.substr(endIndex+1,lastIndex);

         else

            imgFile = imgFilePath;

         var tag = true;

         endIndex = imgFilePath.lastIndexOf(".");

         if (endIndex == -1)

           tag = false;

 

         var ImgName = imgFilePath.substr(endIndex+1,lastIndex);

         ImgName = ImgName.toUpperCase();

 

         if (ImgName !="JPG"){

             tag=false;

         }

         if (!tag) {

             alert("上传图片的文件类型必须为: *.jpg,请重新选择!")

             Upload.clear(obj);

             returnfalse;

         }

          document.form1.submit();

      }

       function getImgFullPath(obj) {

           if (obj) {

              //ie

              if (window.navigator.userAgent.indexOf("MSIE") >= 1) {

                  obj.select();

                  obj.blur();

                  //console.log(document.selection.createRange().text);

                  return document.selection.createRange().text;

              }

              //firefox

              elseif (window.navigator.userAgent.indexOf("Firefox") >= 1) {

                  if (obj.files) {

                      return obj.files.item(0).getAsDataURL();

                     // return window.URL.createObjectURL(obj.files[0]);

                  }

                  return obj.value;

              }

              // chrome

              elseif(window.navigator.userAgent.toLowerCase().indexOf('chrome') > -1 ){

                //alert("我是chrome");

               //alert(document.all.imgFile.value;);

                 return document.all.imgFile.value;

              }

              return obj.value;

          }

       }

        function closeWin1(){

           var k=window.dialogArguments;

        var fileRoot = document.getElementById("ImgPath").value;

        if(fileRoot=="8"){

             //alert("0");

             k.document.getElementById("photoNo").value ="8";

        }

        if(fileRoot!="" &&fileRoot!=undefined){

             k.document.getElementById("img").src =fileRoot;

         //k.document.getElementById("img").attr("src") =fileRoot;

         k.document.getElementById("file").value =fileRoot;

         k.document.getElementById("photo").value =fileRoot;

        // alert(k.document.getElementById("photo").value);

         window.close();

             }else{

                  alert("图片上传失败,请重新上传");

                window.close();

             }

        }

        function closeWin2(){

        var fileRoot = document.getElementById("ImgPath").value;

             if(fileRoot!="" &&fileRoot!=undefined){

             var k=window.dialogArguments;

              k.document.getElementById("img").src =fileRoot;

              k.document.getElementById("file").value =fileRoot;

              k.document.getElementById("photo").value =fileRoot;

                window.close();

             }else{

                alert("图片上传失败,请重新上传");

                window.close();

             }

        }

    </script>

  </head>

  <body  STYLE="margin-left:auto;margin-right:auto;OVERFLOW-X: hidden; OVERFLOW: hidden;" text-align:center>

    <input type="hidden" id="ImgPath" name="ImgPath"  />

    <form name="form1" id="form1" method=post enctype="multipart/form-data" action="<%=path%>/imgUpload" >

    <div style="bgcolor=#d9d9d9" >

    <!-- <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0" > -->

       <table border=0 cellPadding=0 cellSpacing=0 align="bottom">

       <tr><td >

       <fieldset  style="width:300;height:150;border:2px groove; Background-color:#ff9966;" align=center>

               <legend>&nbsp;图片上传&nbsp;&nbsp;<font color='red'>*.jpg</font></legend>

                <input type="file" name="imgFile" id="imgFile" maxlength="160" onchange="checkImgType(this);" width="280px"/>&nbsp;</br>

                <input type="button"  value="完成头像上传" onclick="closeWin1();"width="240px"  class="submit"/>&nbsp;

                <input type="button"  value="关闭上传窗口" onclick="closeWin2();"width="240px"  class="submit"/>&nbsp;

           </fieldset>

       </td></tr></br></br>

       <tr>

           <spanstyle="height:42px;line-height:25px;padding-left:10px;color:red;"><<选择本地照片,进行头像切割,点击完成上传注册页面会显示您的头像,如未显示,请重新上传>></span>

        </tr>

       </br></br>

       </table>

    <!--</table> -->

       </div>

    </form>

  </body>

</html>

 

 

3 index.jsp 把图片提交到 servlet 传给服务器

package net.liuzd.tools.images;

import java.awt.image.BufferedImage;

import java.io.File;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Calendar;

import java.util.Date;

import java.util.Iterator;

import java.util.List;

import javax.imageio.ImageIO;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.apache.log4j.Logger;

publicclass ImgUploadServlet extends HttpServlet {

    privatestaticfinal Logger log = Logger.getLogger(ImgUploadServlet.class);

    privatestaticfinallongserialVersionUID = 1L;

    publicstaticfinal String IMGROOT = "/uploads/";

    publicvoid doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        doPost(request,response);

    }

 

    @SuppressWarnings("unchecked")

    publicvoid doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        String userWebAppPath = getWebAppPath();

        /**检查是否有图片上传文件夹*/

        checkImageDir(userWebAppPath);

 

        /**图片上传的相对路径*/

        String imgUploadPath = null;

        String imgWebAppPath = null;

        /**图片后缀*/

        String imgFileExt = null;

 

        /**图片名称:以当前日期*/

        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmss");

        String imgFileId = formatter.format(new Date());

 

        //图片初始化高度与宽度

        String width = null;

        String height = null;

 

        int imgWidth = 0;

        int imgHeight = 0;

        int imgSrcWidth = 0;

        int imgSrcHeight = 0;

        try {

        log.info("开始上传文件... ");

         height = "400";

             width = "300";

             imgWidth = Integer.parseInt(width);

             imgHeight = Integer.parseInt(height);

             File uploadPath = new File(userWebAppPath);//上传文件目录

         if (!uploadPath.exists()) {

             uploadPath.mkdirs();

         }

         // 临时文件目录

//           File tempPathFile = new File(userWebAppPath);

//           if (!tempPathFile.exists()) {

//              tempPathFile.mkdirs();

//           }

         try {

             // Create a factory for disk-based file items

             DiskFileItemFactory factory = new DiskFileItemFactory();

 

             // Set factory constraints

//              factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb

//              factory.setRepository(tempPathFile);//设置缓冲区目录

 

             // Create a new file upload handler

             ServletFileUpload upload = new ServletFileUpload(factory);

 

             // Set overall request size constraint

             //upload.setSizeMax(4194304*1024); // 设置最大文件尺寸,这里是4MB

 

             List<FileItem> items = upload.parseRequest(request);//得到所有的文件此处切记不可以在index.jsp的表单中含有其他非文件类型<input> 避免出错因为FileItem 有属性 isFormField 非文件属性时肯定出错

             Iterator<FileItem> i = items.iterator();

             while (i.hasNext()) {

                FileItem item = (FileItem) i.next();

                String imgName = item.getName();

                int myIndex = imgName.lastIndexOf(".");

                 imgFileExt  = imgName.substring(myIndex);//获取文件类型

                     //组装图片真实名称

                     imgFileId += System.currentTimeMillis() + imgFileExt;

                if(imgFileId != null) {

             File fullFile = new File(imgFileId);

             File savedFile = new File(uploadPath, fullFile.getName());

             item.write(savedFile);

                }

             }

 

              //图片的相对路径

                imgUploadPath = IMGROOT +getSysdate().replace("/","")+"/"+ imgFileId;

                imgWebAppPath = userWebAppPath +imgFileId;

                //检查图片大小

                BufferedImage src = ImageIO.read(new File(imgWebAppPath)); // 读入文件

                imgSrcWidth = src.getWidth(); // 得到源图宽

                //重新指定大小

                imgWidth = imgSrcWidth > imgWidth ? imgWidth : imgSrcWidth;

 

                imgSrcHeight = src.getHeight(); // 得到源图长

                imgHeight = imgSrcHeight > imgHeight ? imgHeight : imgSrcHeight;

 

                //按照图片的设置大小生成

                ImageCut.scale(imgWebAppPath, imgWebAppPath,imgWidth,imgHeight);

                 File f = new File(imgWebAppPath);

                 if(f.exists()){

                   log.info("创建"+imgWidth+"*"+imgHeight+"图片成功");

                 }

         } catch (Exception e) {

             e.printStackTrace();

         }

 

        }catch(Exception ex){

            ex.printStackTrace();

        }

        log.info("上传文件完成... ");///apply/jQueryImgCrop

        String path = "/apply/jQueryImgCrop/imgcrop.jsp?tag=0&oldImgPath="+imgUploadPath+"&imgFileExt="+imgFileExt+"&imgRoot="+IMGROOT+"&width="+imgWidth+"&height="+imgHeight;

        request.getRequestDispatcher(path).forward(request,response);

 

    }

 

    private String getWebAppPath(){

        String webAppPath = this.getServletContext().getRealPath("/");

        String userWebAppPath = webAppPath+IMGROOT+getSysdate().replace("/","")+"/";

        return userWebAppPath;

    }

 

    privatevoid checkImageDir(String userWebAppPath) {

         File file = new File(userWebAppPath);

         if(!file.exists()){

             file.mkdir();

         }

    }

    /**

     * 取得系统当前时间

     * @return String

     */

    publicstatic String getSysdate() {

        Calendar cal = Calendar.getInstance();

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");

        return formatter.format(cal.getTime());

    }

}

 

 

4 剪切页面

 

 

<%@ page language="java"  pageEncoding="UTF-8"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

  <head>

    <basehref="<%=basePath%>">

    <title>图片剪辑</title>

    <metahttp-equiv="pragma"content="no-cache">

    <metahttp-equiv="cache-control"content="no-cache">

    <metahttp-equiv="expires"content="0">

    <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">

    <metahttp-equiv="description"content="This is my page">

    <link rel="stylesheet" href="apply/jQueryImgCrop/styles/jquery.Jcrop.css" type="text/css" />

    <link rel="stylesheet" href="apply/jQueryImgCrop/styles/demos.css" type="text/css" />

    <script src="apply/jQueryImgCrop/scripts/jquery.min.js"></script>

    <script src="apply/jQueryImgCrop/scripts/jquery.Jcrop.js"></script>

  </head>

 <body STYLE='OVERFLOW:SCROLL;OVERFLOW-X:HIDDEN;OVERFLOW-Y:HIDDEN' onblur="window.focus()" onload="sizePage();">

    <form name=form1 method=post action="<%=path%>/imgCrop">

    <table width="85%" border="0" align="center" cellpadding="0" cellspacing="0" >

           <tr>

           <!-- <td id="cropTd" style="display:none"><input type="button" value="剪切照片" id="cropButton"/></td> -->

           </tr>

                                   <br/>

            <tr>

              <td id="imgTd" style="width:${param.width}px;height:${param.height}px;" align="center" style="padding-top:5px;">

                   <c:choose>

                      <c:when test="${param.tag eq 0}">

                         <img  src="<%=path%>${param.oldImgPath}" id="imgCrop" name="imgCrop" border="0" />

                      </c:when>

                      <c:when test="${param.tag eq 1}">

                         <img  src="<%=path%>${param.imgName}" id="imgCrop" name="imgCrop" border="0" />

                      </c:when>

                   </c:choose>

            </td>

            <td>

             <span style="height:42px;line-height:25px;padding-left:10px;color:red;">进入该页面,只需拖动光亮部分选取即可,不必调节大小,然后点击下方剪切图片完成剪切,提示剪切成功之后按照步骤逐步关闭本窗口即可,如果点击错误或者大小不易调节,请刷新该页面即可</span>

            </td>

           </tr>

            <tr>

               <td>

                  <label>宽度<input type="text" size="4" id="labelW" name="labelW" />

                  <label>高度<input type="text" size="4" id="labelH" name="labelH" />

               </td>

           </tr>

            </table>

           <div id="cropTd" style="display:none" align="center">

              <input type="button" value="剪切照片" id="cropButton"/>&nbsp;&nbsp;&nbsp;&nbsp;

              <input type="button" value="刷新页面" id="cropButton2" onclick="window.location.reload();"/>

           </div>

    <input type="hidden"  id="x" name="x" />

    <input type="hidden"  id="y" name="y" />

    <input type="hidden"  id="x2" name="x2" />

    <input type="hidden"  id="y2" name="y2" />

    <input type="hidden"  id="w" name="w" />

    <input type="hidden"  id="h" name="h" />

    <!-- 源图片宽度和高度 -->

    <input type="hidden"  id="width" name="width" value="${param.width}"/>

    <input type="hidden"  id="height" name="height" value="${param.height}"/>

    <input type="hidden"  id="oldImgPath" name="oldImgPath" value="${param.oldImgPath}"/>

    <input type="hidden"  id="imgRoot" name="imgRoot" value="${param.imgRoot}"/>

    <input type="hidden"  id="imgFileExt" name="imgFileExt" value="${param.imgFileExt}"/>

    </form>

  </body>

</html>

<scripttype="text/javascript">

    jQuery(document).ready(function(){

       var jcrop_api;

       if(jQuery('#width').val()>=240&&jQuery('#height').val()>=320){

           jQuery('#imgCrop').Jcrop({

           onChange: showCoords,

           onSelect: showCoords,

           setSelect:[0,0,240,320],

           sideHandles:false , //允许四边缩放

           drawBorders:false ,//绘制边框

           dragEdges:false , //允许拖动边框

           allowResize:false,

           allowSelect:false

       });

       }else{

           alert("上传的文件不符规定,像素(宽高)必须大于等于(>=)240*320");

           jQuery('#cropNew').css("display","");

           window.close();

       }

       $("#can_click").change(function(e){

           jcrop_api.setOptions({allowSelect: !!this.checked});

           jcrop_api.focus();

       });

       $("#can_size").change(function(e){

           jcrop_api.setOptions({allowResize: !!this.checked});

           jcrop_api.focus();

       });

       function sizePage(){

            window.resizeTo(600,600);//调整大小

           }

       jQuery('#cropButton').click(function(){

               var x = jQuery("#x").val();

              var y = jQuery("#y").val();

              var w = jQuery("#w").val();

              var h = jQuery("#h").val();

 

              if(w == 0 || h == 0 ){

                  alert("您还没有选择图片的剪切区域,不能进行剪切图片!");

                  return;

              }

              if(confirm("图片剪切成功,请点击确定关闭窗口")){

               if (window.navigator.userAgent.indexOf("MSIE") >= 1){

                     $.ajax({

                     type: "POST",

                     url: $('form').attr("action"),

                     //url:ImgUploadServlet,

                     data: $('form').serialize(),

                     success: function(msg){

                         //alert( "Data Saved: " + msg );

                         window.opener.document.getElementById("ImgPath").value = msg;

                         //window.opener.close();

                         window.opener = "whocares";

                         window.close();

                     }

                  });

               }

               elseif(window.navigator.userAgent.toLowerCase().indexOf('chrome') > -1){

                     //alert("chrome 提交");

                     $.ajax({

                     type: "POST",

                     url: $('form').attr("action"),

                     //url:ImgUploadServlet,

                     data: $('form').serialize(),

                     success: function(msg){

                         //alert( "Data Saved: " + msg);

                         window.opener.opener.document.getElementById("img").src =fileRoot;

                        window.opener.opener.document.getElementById("file").value =fileRoot;

                         window.close();

                     }

                  });

               }

              }

        });

    });

    function sizePage(){

     window.resizeTo(600,600);//调整大小

     window.setResizable(true);

    }

    function showCoords(c)

    {

       jQuery('#x').val(c.x);

       jQuery('#y').val(c.y);

       jQuery('#x2').val(c.x2);

       jQuery('#y2').val(c.y2);

       jQuery('#w').val(c.w);

       jQuery('#h').val(c.h);

       jQuery('#labelX').val(c.x);

       jQuery('#labelY').val(c.y);

       jQuery('#labelX2').val(c.x2);

       jQuery('#labelY2').val(c.y2);

       jQuery('#labelW').val(c.w);

       jQuery('#labelH').val(c.h);

       //显示剪切按键

       jQuery('#cropTd').css("display","");

    }

</script>

 

5 传给其他servlet 进行进切  通过ajax

 

package net.liuzd.tools.images;

import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

import java.text.SimpleDateFormat;

import java.util.Date;

 

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.apache.log4j.Logger;

import org.caexpo.common.util.Util;

 

public class ImgCropServlet extends HttpServlet {

 

    private static final long serialVersionUID = 1L;

    private static final Logger log = Logger.getLogger(ImgCropServlet.class);

    public void doGet(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        doPost(request, response);

 

    }

 

    public void doPost(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

 

        try {

                            System.out.println("x: " + request.getParameter("x") + "," + request.getParameter("y") + "," + request.getParameter("w") + "," + request.getParameter("h"));

 

                            // 用户经过剪辑后的图片的大小

                            Integer x = Integer.parseInt(request.getParameter("x"));

                            Integer y = Integer.parseInt(request.getParameter("y"));

                            Integer w = Integer.parseInt(request.getParameter("w"));

                            Integer h = Integer.parseInt(request.getParameter("h"));

 

                            //获取原显示图片路径

                            String oldImgPath = request.getParameter("oldImgPath");

                            //图片后缀

                            String imgFileExt = request.getParameter("imgFileExt");

                            String imgRoot =  request.getParameter("imgRoot");

 

                            Integer width = Integer.parseInt(request.getParameter("width"));

                            Integer height = Integer.parseInt(request.getParameter("height"));

 

                            //WEB应用程序根路径

                            String webAppPath = getServletContext().getRealPath("/");

 

                            /**图片名称:以当前日期*/

                            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmmss");

                            String imgFileId = formatter.format(new Date());

                            String imgName =  imgRoot +Util.getSysdate().replace("/","")+"/"+ imgFileId + System.currentTimeMillis() + "." + imgFileExt;

                            //组装图片真实名称

                            String createImgPath = webAppPath + imgName;

                            // E:\Chris_Eclipse\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp9\wtpwebapps\expo\

                            //之前上传的图片路径

                            webAppPath =webAppPath.substring(0, webAppPath.lastIndexOf(File.separator))+ oldImgPath;

                            File oldFile2 = new File(webAppPath);

                            if(oldFile2.exists()){

                                     log.info("图片切割开始...=========================================");

                                     log.info("原图片路径: " + webAppPath + ",新图片路径: " + createImgPath);

 

                                //进行剪切图片操作

                                ImageCut.abscut(webAppPath, createImgPath, x,y,w, h);

                                log.info("图片切割结束...========================================= ");

                                 File f = new File(createImgPath);

                                 if(f.exists()){

                                          log.info("剪切图片大小: "+w+"*"+h+"图片成功!");

                                }

 

                                 File oldFile = new File(webAppPath);

                                      if(oldFile.exists()){

                                                oldFile.delete();

                                      }

 

                                     String path = "/apply/registration_purchasers_1.html?tag=1&oldImgPath="+oldImgPath+"&imgFileExt="+imgFileExt+"&imgRoot="+imgRoot + "&imgName="+imgName+"&height=" + height + "&width=" + width;

                                     log.info("把剪切值传给registration_purchasers_1.html: " + path);

                                     log.info("服务器上目标图片物理路径: " + webAppPath);

                                     log.info("图片根文件夹: " + imgRoot);

                                     response.setContentType("text/html; charset=utf-8");

                                     StringBuffer write = new StringBuffer();

                                     log.info("服务器上目标图片相对路径:: " + createImgPath);

 

                                     //String[]createImg = createImgPath.split(imgRoot);

 

                                     //String newCreateImg = createImg[0]+"uploads"+File.separator+createImg[1];

                                     //E:\Chris_Eclipse\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\expo\ 201305071159231367899163863.jpg

                                     String url = request.getRequestURL().toString();

                                     url = url.replace("/imgCrop", "")+imgName;

                                     String dd = url.replaceAll("/imgCrop", "");

                                     log.info("服务器URL: " + dd);

                                     //http://localhost:8088/expo/imgCrop

                                     log.info("剪切之后服务器的图片路径: " + url);

                                     write.append(url);

                                     response.getWriter().write(write.toString());

 

                            }else{

                                     request.setAttribute("_JavaScript","alert('对不起,您的操作有误,请关闭上传窗口并重新操作!')");

                                     PrintWriter out = response.getWriter();

                                     out.print("8");

                            }

 

                   } catch (Exception e) {

                            PrintWriter out = response.getWriter();

                            out.print("8");

                   }

 

    }

 

}

  • 大小: 54.7 KB
  • 大小: 41.9 KB
  • 大小: 91.3 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics