- 浏览: 4166 次
- 性别:
- 来自: 深圳
最新评论
收藏列表
标题 | 标签 | 来源 | |
java上传文件到微信服务器 | java上传文件到微信服务器 | ||
package com.sz.kcygl.common.util; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class FileUpload { /** * 模拟form表单的形式 ,上传文件 以输出流的形式把文件写入到url中,然后用输入流来获取url的响应 * * @param url 请求地址 form表单url地址 * @param filePath 文件在服务器保存路径 * @return String url的响应信息返回值 * @throws IOException */ public static String send(String url, String filePath) throws IOException { String result = null; File file = new File(filePath); if (!file.exists() || !file.isFile()) { throw new IOException("文件不存在"); } /** * 第一部分 */ URL urlObj = new URL(url); // 连接 HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); /** * 设置关键值 */ con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式 con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); // post方式不能使用缓存 // 设置请求头信息 con.setRequestProperty("Connection", "Keep-Alive"); con.setRequestProperty("Charset", "UTF-8"); // 设置边界 String BOUNDARY = "----------" + System.currentTimeMillis(); con.setRequestProperty("Content-Type", "multipart/form-data; boundary="+ BOUNDARY); // 请求正文信息 // 第一部分: StringBuilder sb = new StringBuilder(); sb.append("--"); // 必须多两道线 sb.append(BOUNDARY); sb.append("\r\n"); sb.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"\r\n"); sb.append("Content-Type:application/octet-stream\r\n\r\n"); byte[] head = sb.toString().getBytes("utf-8"); // 获得输出流 OutputStream out = new DataOutputStream(con.getOutputStream()); // 输出表头 out.write(head); // 文件正文部分 // 把文件已流文件的方式 推入到url中 DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); // 结尾部分 byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线 out.write(foot); out.flush(); out.close(); StringBuffer buffer = new StringBuffer(); BufferedReader reader = null; try { // 定义BufferedReader输入流来读取URL的响应 reader = new BufferedReader(new InputStreamReader(con.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { //System.out.println(line); buffer.append(line); } if(result==null){ result = buffer.toString(); } } catch (IOException e) { System.out.println("发送POST请求出现异常!" + e); e.printStackTrace(); throw new IOException("数据读取异常"); } finally { if(reader!=null){ reader.close(); } } JSONObject jsonObj = JSONObject.fromObject(result); String mediaId = jsonObj.getString("media_id"); return mediaId; } public static void main(String[] args) throws IOException { String filePath = "D:/tomcat/apache-tomcat-6.0.37/webapps/Allianture_frame/upload/test3_20140117094014814.jpg"; String sendUrl = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=yeQEu_OrXQanGC_G56BZ7IKJDCQCaO0ryDWKX2N2JDzGRGuiZACTGjsQXW-S-K1fgm_MViG_R5AwIEBhKKCNmUevg0H3ksfzlIfkFcP1y8g2st2LYwloL_iPqhedlT5_Z1zSM2mZSmu6cI54sayMPw&type=image"; String result = null; FileUpload fileUpload = new FileUpload(); result = fileUpload.send(sendUrl, filePath); System.out.println(result); } } |
|||
java图片切割 | Java图片切割 | ||
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String Pic = (String) request.getParameter("p"); int PointX = Integer.parseInt(request.getParameter("x")); int PointY = Integer.parseInt(request.getParameter("y")); int CutWidth = Integer.parseInt(request.getParameter("w")); int CutHeight = Integer.parseInt(request.getParameter("h")); // 图片宽度 int PicWidth = Integer.parseInt(request.getParameter("pw")); // 图片高度 int PicHeight = Integer.parseInt(request.getParameter("ph")); response.setContentType("image/jpeg"); response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); HttpSession session = request.getSession(); String picPath = Pic; String path = request.getRealPath(picPath); ServletOutputStream responseOutputStream = response.getOutputStream(); cut(path, responseOutputStream, CutWidth, CutHeight, PointX, PointY, PicWidth, PicHeight); // 以下关闭输入流! responseOutputStream.flush(); responseOutputStream.close(); } /** * 图片切割 * @param srcImageFile 图片地址 * @param responseOutputStream servlet输出流 * @param w 切割宽度 * @param h 切割高度 * @param x1 开始x结点(left) * @param y1 开始y结点(top) * @param sw 图片宽度 * @param sh 图片高度 */ public void cut(String srcImageFile,ServletOutputStream responseOutputStream, int w, int h, int x1, int y1, int sw, int sh) { try { // http://localhost:8080/ImpCra/createServlet?p=Sunset.jpg&x=117&y=201&w=61&h=50&pw=300&ph=400 Image img; ImageFilter cropFilter; // 读取源图像 BufferedImage bi = ImageIO.read(new File(srcImageFile)); if (sw >= w && sh >= h) { Image image = bi.getScaledInstance(sw, sh, Image.SCALE_DEFAULT); // 剪切起始坐标点 int x = x1; int y = y1; int destWidth = w; // 切片宽度 int destHeight = h; // 切片高度 // 图片比例 double pw = sw; double ph = sh; double m = (double) sw / pw; double n = (double) sh / ph; int wth = (int) (destWidth * m); int hth = (int) (destHeight * n); int xx = (int) (x * m); int yy = (int) (y * n); // 四个参数分别为图像起点坐标和宽高 // 即: CropImageFilter(int x,int y,int width,int height) cropFilter = new CropImageFilter(xx, yy, wth, hth); img = Toolkit.getDefaultToolkit().createImage( new FilteredImageSource(image.getSource(), cropFilter)); BufferedImage tag = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics g = tag.getGraphics(); g.drawImage(img, 0, 0, null); // 绘制缩小后的图 g.dispose(); // 输出为文件 ImageIO.write(tag, "JPEG", responseOutputStream); } } catch (Exception e) { e.printStackTrace(); } } <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>JavaScript 图片切割效果(带拖放、缩放效果) </title> </head> <body> <style type="text/css"> #rRightDown,#rLeftDown,#rLeftUp,#rRightUp,#rRight,#rLeft,#rUp,#rDown{position:absolute;background:#F00;width:5px; height:5px; z-index:500; font-size:0;} #dragDiv{border:1px solid #000000;} </style> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="50%"> <div id="bgDiv" style="width:400px; height:500px;"> <div id="dragDiv"> <div id="rRightDown" style="right:0; bottom:0;"> </div> <div id="rLeftDown" style="left:0; bottom:0;"> </div> <div id="rRightUp" style="right:0; top:0;"> </div> <div id="rLeftUp" style="left:0; top:0;"> </div> <div id="rRight" style="right:0; top:50%;"> </div> <div id="rLeft" style="left:0; top:50%;"> </div> <div id="rUp" style="top:0; left:50%;"> </div> <div id="rDown" style="bottom:0;left:50%;"></div> </div> </div> </td> <td><div id="viewDiv" style="width:200px; height:200px;"> </div></td> </tr> </table> <script> var $ = function (id) { return "string" == typeof id ? document.getElementById(id) : id; }; var isIE = (document.all) ? true : false; function addEventHandler(oTarget, sEventType, fnHandler) { if (oTarget.addEventListener) { oTarget.addEventListener(sEventType, fnHandler, false); } else if (oTarget.attachEvent) { oTarget.attachEvent("on" + sEventType, fnHandler); } else { oTarget["on" + sEventType] = fnHandler; } }; function removeEventHandler(oTarget, sEventType, fnHandler) { if (oTarget.removeEventListener) { oTarget.removeEventListener(sEventType, fnHandler, false); } else if (oTarget.detachEvent) { oTarget.detachEvent("on" + sEventType, fnHandler); } else { oTarget["on" + sEventType] = null; } }; var Class = { create: function() { return function() { this.initialize.apply(this, arguments); } } } Object.extend = function(destination, source) { for (var property in source) { destination[property] = source[property]; } return destination; } //拖放程序 var Drag = Class.create(); Drag.prototype = { //拖放对象,触发对象 initialize: function(obj, drag, options) { var oThis = this; this._obj = $(obj);//拖放对象 this.Drag = $(drag);//触发对象 this._x = this._y = 0;//记录鼠标相对拖放对象的位置 //事件对象(用于移除事件) this._fM = function(e){ oThis.Move(window.event || e); } this._fS = function(){ oThis.Stop(); } this.SetOptions(options); this.Limit = !!this.options.Limit; this.mxLeft = parseInt(this.options.mxLeft); this.mxRight = parseInt(this.options.mxRight); this.mxTop = parseInt(this.options.mxTop); this.mxBottom = parseInt(this.options.mxBottom); this.onMove = this.options.onMove; this._obj.style.position = "absolute"; addEventHandler(this.Drag, "mousedown", function(e){ oThis.Start(window.event || e); }); }, //设置默认属性 SetOptions: function(options) { this.options = {//默认值 Limit: false,//是否设置限制(为true时下面参数有用,可以是负数) mxLeft: 0,//左边限制 mxRight: 0,//右边限制 mxTop: 0,//上边限制 mxBottom: 0,//下边限制 onMove: function(){}//移动时执行 }; Object.extend(this.options, options || {}); }, //准备拖动 Start: function(oEvent) { //记录鼠标相对拖放对象的位置 this._x = oEvent.clientX - this._obj.offsetLeft; this._y = oEvent.clientY - this._obj.offsetTop; //mousemove时移动 mouseup时停止 addEventHandler(document, "mousemove", this._fM); addEventHandler(document, "mouseup", this._fS); //使鼠标移到窗口外也能释放 if(isIE){ addEventHandler(this.Drag, "losecapture", this._fS); this.Drag.setCapture(); }else{ addEventHandler(window, "blur", this._fS); } }, //拖动 Move: function(oEvent) { //清除选择(ie设置捕获后默认带这个) window.getSelection && window.getSelection().removeAllRanges(); //当前鼠标位置减去相对拖放对象的位置得到offset位置 var iLeft = oEvent.clientX - this._x, iTop = oEvent.clientY - this._y; //设置范围限制 if(this.Limit){ //获取超出长度 var iRight = iLeft + this._obj.offsetWidth - this.mxRight, iBottom = iTop + this._obj.offsetHeight - this.mxBottom; //这里是先设置右边下边再设置左边上边,可能会不准确 if(iRight > 0) iLeft -= iRight; if(iBottom > 0) iTop -= iBottom; if(this.mxLeft > iLeft) iLeft = this.mxLeft; if(this.mxTop > iTop) iTop = this.mxTop; } //设置位置 this._obj.style.left = iLeft + "px"; this._obj.style.top = iTop + "px"; //附加程序 this.onMove(); }, //停止拖动 Stop: function() { //移除事件 removeEventHandler(document, "mousemove", this._fM); removeEventHandler(document, "mouseup", this._fS); if(isIE){ removeEventHandler(this.Drag, "losecapture", this._fS); this.Drag.releaseCapture(); }else{ removeEventHandler(window, "blur", this._fS); } } }; //缩放程序 var Resize = Class.create(); Resize.prototype = { //缩放对象 initialize: function(obj, options) { var oThis = this; this._obj = $(obj);//缩放对象 this._right = this._down = this._left = this._up = 0;//坐标参数 this._scale = 1;//比例参数 this._touch = null;//当前触发对象 //用currentStyle(ff用getComputedStyle)取得最终样式 var _style = this._obj.currentStyle || document.defaultView.getComputedStyle(this._obj, null); this._xBorder = parseInt(_style.borderLeftWidth) + parseInt(_style.borderRightWidth); this._yBorder = parseInt(_style.borderTopWidth) + parseInt(_style.borderBottomWidth); //事件对象(用于移除事件) this._fR = function(e){ oThis.Resize(e); } this._fS = function(){ oThis.Stop(); } this.SetOptions(options); this.Limit = !!this.options.Limit; this.mxLeft = parseInt(this.options.mxLeft); this.mxRight = parseInt(this.options.mxRight); this.mxTop = parseInt(this.options.mxTop); this.mxBottom = parseInt(this.options.mxBottom); this.MinWidth = parseInt(this.options.MinWidth); this.MinHeight = parseInt(this.options.MinHeight); this.Scale = !!this.options.Scale; this.onResize = this.options.onResize; this._obj.style.position = "absolute"; }, //设置默认属性 SetOptions: function(options) { this.options = {//默认值 Limit: false,//是否设置限制(为true时下面mx参数有用) mxLeft: 0,//左边限制 mxRight: 0,//右边限制 mxTop: 0,//上边限制 mxBottom: 0,//下边限制 MinWidth: 50,//最小宽度 MinHeight: 50,//最小高度 Scale: false,//是否按比例缩放 onResize: function(){}//缩放时执行 }; Object.extend(this.options, options || {}); }, //设置触发对象 Set: function(resize, side) { var oThis = this, resize = $(resize), _fun, _cursor; if(!resize) return; //根据方向设置 _fun是缩放时执行的程序 _cursor是鼠标样式 switch (side.toLowerCase()) { case "up" : _fun = function(e){ if(oThis.Scale){ oThis.scaleUpRight(e); }else{ oThis.SetUp(e); } }; _cursor = "n-resize"; break; case "down" : _fun = function(e){ if(oThis.Scale){ oThis.scaleDownRight(e); }else{ oThis.SetDown(e); } }; _cursor = "n-resize"; break; case "left" : _fun = function(e){ if(oThis.Scale){ oThis.scaleLeftUp(e); }else{ oThis.SetLeft(e); } }; _cursor = "e-resize"; break; case "right" : _fun = function(e){ if(oThis.Scale){ oThis.scaleRightDown(e); }else{ oThis.SetRight(e); } }; _cursor = "e-resize"; break; case "left-up" : _fun = function(e){ if(oThis.Scale){ oThis.scaleLeftUp(e); }else{ oThis.SetLeft(e); oThis.SetUp(e); } }; _cursor = "nw-resize"; break; case "right-up" : _fun = function(e){ if(oThis.Scale){ oThis.scaleRightUp(e); }else{ oThis.SetRight(e); oThis.SetUp(e); } }; _cursor = "ne-resize"; break; case "left-down" : _fun = function(e){ if(oThis.Scale){ oThis.scaleLeftDown(e); }else{ oThis.SetLeft(e); oThis.SetDown(e); } }; _cursor = "ne-resize"; break; case "right-down" : default : _fun = function(e){ if(oThis.Scale){ oThis.scaleRightDown(e); }else{ oThis.SetRight(e); oThis.SetDown(e); } }; _cursor = "nw-resize"; } //设置触发对象 resize.style.cursor = _cursor; addEventHandler(resize, "mousedown", function(e){ oThis._fun = _fun; oThis._touch = resize; oThis.Start(window.event || e); }); }, //准备缩放 Start: function(oEvent, o) { //防止冒泡 if(isIE){ oEvent.cancelBubble = true; } else { oEvent.stopPropagation(); } //计算样式初始值 this.style_width = this._obj.offsetWidth; this.style_height = this._obj.offsetHeight; this.style_left = this._obj.offsetLeft; this.style_top = this._obj.offsetTop; //设置缩放比例 if(this.Scale){ this._scale = this.style_width / this.style_height; } //计算当前边的对应另一条边的坐标 例如右边缩放时需要左边界坐标 this._left = oEvent.clientX - this.style_width; this._right = oEvent.clientX + this.style_width; this._up = oEvent.clientY - this.style_height; this._down = oEvent.clientY + this.style_height; //如果有范围 先计算好范围内最大宽度和高度 if(this.Limit){ this._mxRight = this.mxRight - this._obj.offsetLeft; this._mxDown = this.mxBottom - this._obj.offsetTop; this._mxLeft = this.mxLeft + this.style_width + this._obj.offsetLeft; this._mxUp = this.mxTop + this.style_height + this._obj.offsetTop; } //mousemove时缩放 mouseup时停止 addEventHandler(document, "mousemove", this._fR); addEventHandler(document, "mouseup", this._fS); //使鼠标移到窗口外也能释放 if(isIE){ addEventHandler(this._touch, "losecapture", this._fS); this._touch.setCapture(); }else{ addEventHandler(window, "blur", this._fS); } }, //缩放 Resize: function(e) { //没有触发对象的话返回 if(!this._touch) return; //清除选择(ie设置捕获后默认带这个) window.getSelection && window.getSelection().removeAllRanges(); //执行缩放程序 this._fun(window.event || e); //设置样式 //因为计算用的offset是把边框算进去的所以要减去 this._obj.style.width = this.style_width - this._xBorder + "px"; this._obj.style.height = this.style_height - this._yBorder + "px"; this._obj.style.top = this.style_top + "px"; this._obj.style.left = this.style_left + "px"; //附加程序 this.onResize(); }, //普通缩放 //右边 SetRight: function(oEvent) { //当前坐标位置减去左边的坐标等于当前宽度 this.repairRight(oEvent.clientX - this._left); }, //下边 SetDown: function(oEvent) { this.repairDown(oEvent.clientY - this._up); }, //左边 SetLeft: function(oEvent) { //右边的坐标减去当前坐标位置等于当前宽度 this.repairLeft(this._right - oEvent.clientX); }, //上边 SetUp: function(oEvent) { this.repairUp(this._down - oEvent.clientY); }, //比例缩放 //比例缩放右下 scaleRightDown: function(oEvent) { //先计算宽度然后按比例计算高度最后根据确定的高度计算宽度(宽度优先) this.SetRight(oEvent); this.repairDown(parseInt(this.style_width / this._scale)); this.repairRight(parseInt(this.style_height * this._scale)); }, //比例缩放左下 scaleLeftDown: function(oEvent) { this.SetLeft(oEvent); this.repairDown(parseInt(this.style_width / this._scale)); this.repairLeft(parseInt(this.style_height * this._scale)); }, //比例缩放右上 scaleRightUp: function(oEvent) { this.SetRight(oEvent); this.repairUp(parseInt(this.style_width / this._scale)); this.repairRight(parseInt(this.style_height * this._scale)); }, //比例缩放左上 scaleLeftUp: function(oEvent) { this.SetLeft(oEvent); this.repairUp(parseInt(this.style_width / this._scale)); this.repairLeft(parseInt(this.style_height * this._scale)); }, //这里是高度优先用于上下两边(体验更好) //比例缩放下右 scaleDownRight: function(oEvent) { this.SetDown(oEvent); this.repairRight(parseInt(this.style_height * this._scale)); this.repairDown(parseInt(this.style_width / this._scale)); }, //比例缩放上右 scaleUpRight: function(oEvent) { this.SetUp(oEvent); this.repairRight(parseInt(this.style_height * this._scale)); this.repairUp(parseInt(this.style_width / this._scale)); }, //修正程序 //修正右边 repairRight: function(iWidth) { //右边和下边只要设置宽度和高度就行 //当少于最少宽度 if (iWidth < this.MinWidth){ iWidth = this.MinWidth; } //当超过当前设定的最大宽度 if(this.Limit && iWidth > this._mxRight){ iWidth = this._mxRight; } //修改样式 this.style_width = iWidth; }, //修正下边 repairDown: function(iHeight) { if (iHeight < this.MinHeight){ iHeight = this.MinHeight; } if(this.Limit && iHeight > this._mxDown){ iHeight = this._mxDown; } this.style_height = iHeight; }, //修正左边 repairLeft: function(iWidth) { //左边和上边比较麻烦 因为还要计算left和top //当少于最少宽度 if (iWidth < this.MinWidth){ iWidth = this.MinWidth; } //当超过当前设定的最大宽度 else if(this.Limit && iWidth > this._mxLeft){ iWidth = this._mxLeft; } //修改样式 this.style_width = iWidth; this.style_left = this._obj.offsetLeft + this._obj.offsetWidth - iWidth; }, //修正上边 repairUp: function(iHeight) { if(iHeight < this.MinHeight){ iHeight = this.MinHeight; } else if(this.Limit && iHeight > this._mxUp){ iHeight = this._mxUp; } this.style_height = iHeight; this.style_top = this._obj.offsetTop + this._obj.offsetHeight - iHeight; }, //停止缩放 Stop: function() { //移除事件 removeEventHandler(document, "mousemove", this._fR); removeEventHandler(document, "mouseup", this._fS); if(isIE){ removeEventHandler(this._touch, "losecapture", this._fS); this._touch.releaseCapture(); }else{ removeEventHandler(window, "blur", this._fS); } this._touch = null; } }; //图片切割 var ImgCropper = Class.create(); ImgCropper.prototype = { //容器对象,拖放缩放对象,图片地址,宽度,高度 initialize: function(container, drag, url, width, height, options) { var oThis = this; //容器对象 this.Container = $(container); this.Container.style.position = "relative"; this.Container.style.overflow = "hidden"; //拖放对象 this.Drag = $(drag); this.Drag.style.cursor = "move"; this.Drag.style.zIndex = 200; if(isIE){ //设置overflow解决ie6的渲染问题(缩放时填充对象高度的问题) this.Drag.style.overflow = "hidden"; //ie下用一个透明的层填充拖放对象 不填充的话onmousedown会失效(未知原因) (function(style){ style.width = style.height = "100%"; style.backgroundColor = "#fff"; style.filter = "alpha(opacity:0)"; })(this.Drag.appendChild(document.createElement("div")).style) } this._pic = this.Container.appendChild(document.createElement("img"));//图片对象 this._cropper = this.Container.appendChild(document.createElement("img"));//切割对象 this._pic.style.position = this._cropper.style.position = "absolute"; this._pic.style.top = this._pic.style.left = this._cropper.style.top = this._cropper.style.left = "0";//对齐 this._cropper.style.zIndex = 100; this._cropper.onload = function(){ oThis.SetPos(); } this.Url = url;//图片地址 this.Width = parseInt(width);//宽度 this.Height = parseInt(height);//高度 this.SetOptions(options); this.Opacity = parseInt(this.options.Opacity); this.dragTop = parseInt(this.options.dragTop); this.dragLeft = parseInt(this.options.dragLeft); this.dragWidth = parseInt(this.options.dragWidth); this.dragHeight = parseInt(this.options.dragHeight); //设置预览对象 this.View = $(this.options.View) || null;//预览对象 this.viewWidth = parseInt(this.options.viewWidth); this.viewHeight = parseInt(this.options.viewHeight); this._view = null;//预览图片对象 if(this.View){ this.View.style.position = "relative"; this.View.style.overflow = "hidden"; this._view = this.View.appendChild(document.createElement("img")); this._view.style.position = "absolute"; } this.Scale = parseInt(this.options.Scale); //设置拖放 this._drag = new Drag(this.Drag, this.Drag, { Limit: true, onMove: function(){ oThis.SetPos(); } }); //设置缩放 this._resize = this.GetResize(); this.Init(); }, //设置默认属性 SetOptions: function(options) { this.options = {//默认值 Opacity: 50,//透明度(0到100) //拖放位置和宽高 dragTop: 0, dragLeft: 0, dragWidth: 100, dragHeight: 100, //缩放触发对象 Right: "", Left: "", Up: "", Down: "", RightDown: "", LeftDown: "", RightUp: "", LeftUp: "", Scale: false,//是否按比例缩放 //预览对象设置 View: "",//预览对象 viewWidth: 100,//预览宽度 viewHeight: 100//预览高度 }; Object.extend(this.options, options || {}); }, //初始化对象 Init: function() { var oThis = this; //设置容器 this.Container.style.width = this.Width + "px"; this.Container.style.height = this.Height + "px"; //设置拖放对象 this.Drag.style.top = this.dragTop + "px"; this.Drag.style.left = this.dragLeft + "px"; this.Drag.style.width = this.dragWidth + "px"; this.Drag.style.height = this.dragHeight + "px"; //设置切割对象 this._pic.src = this._cropper.src = this.Url; this._pic.style.width = this._cropper.style.width = this.Width + "px"; this._pic.style.height = this._cropper.style.height = this.Height + "px"; if(isIE){ this._pic.style.filter = "alpha(opacity:" + this.Opacity + ")"; } else { this._pic.style.opacity = this.Opacity / 100; } //设置预览对象 if(this.View){ this._view.src = this.Url; } //设置拖放 this._drag.mxRight = this.Width; this._drag.mxBottom = this.Height; //设置缩放 if(this._resize){ this._resize.mxRight = this.Width; this._resize.mxBottom = this.Height; this._resize.Scale = this.Scale; } }, //设置获取缩放对象 GetResize: function() { var op = this.options; //有触发对象时才设置 if(op.RightDown || op.LeftDown || op.RightUp || op.LeftUp || op.Right || op.Left || op.Up || op.Down ){ var oThis = this, _resize = new Resize(this.Drag, { Limit: true, onResize: function(){ oThis.SetPos(); } }); //设置缩放触发对象 if(op.RightDown){ _resize.Set(op.RightDown, "right-down"); } if(op.LeftDown){ _resize.Set(op.LeftDown, "left-down"); } if(op.RightUp){ _resize.Set(op.RightUp, "right-up"); } if(op.LeftUp){ _resize.Set(op.LeftUp, "left-up"); } if(op.Right){ _resize.Set(op.Right, "right"); } if(op.Left){ _resize.Set(op.Left, "left"); } if(op.Up){ _resize.Set(op.Up, "up"); } if(op.Down){ _resize.Set(op.Down, "down"); } return _resize; } else { return null; } }, //设置切割 SetPos: function() { var o = this.Drag; //按拖放对象的参数进行切割 this._cropper.style.clip = "rect(" + o.offsetTop + "px " + (o.offsetLeft + o.offsetWidth) + "px " + (o.offsetTop + o.offsetHeight) + "px " + o.offsetLeft + "px)"; //切割预览 if(this.View) this.PreView(); }, //切割预览 PreView: function() { //按比例设置宽度和高度 var o = this.Drag, h = this.viewWidth, w = h * o.offsetWidth / o.offsetHeight; if(w > this.viewHeight){ w = this.viewHeight; h = w * o.offsetHeight / o.offsetWidth; } //获取对应比例尺寸 var scale = h / o.offsetHeight, ph = this.Height * scale, pw = this.Width * scale, pt = o.offsetTop * scale, pl = o.offsetLeft * scale, styleView = this._view.style; //设置样式 styleView.width = pw + "px"; styleView.height = ph + "px"; styleView.top = - pt + "px "; styleView.left = - pl + "px"; //切割预览图 styleView.clip = "rect(" + pt + "px " + (pl + w) + "px " + (pt + h) + "px " + pl + "px)"; } } var ic = new ImgCropper("bgDiv", "dragDiv", "../image/Sunset.jpg", 300, 400, { dragTop: 50, dragLeft: 50, Right: "rRight", Left: "rLeft", Up: "rUp", Down: "rDown", RightDown: "rRightDown", LeftDown: "rLeftDown", RightUp: "rRightUp", LeftUp: "rLeftUp", View: "viewDiv", viewWidth: 200, viewHeight: 200 }) </script> <script> //设置图片大小 function Size(w, h){ ic.Width = w; ic.Height = h; ic.Init(); } //换图片 function Pic(url){ ic.Url = url; ic.Init(); } //设置透明度 function Opacity(i){ ic.Opacity = i; ic.Init(); } //是否使用比例 function Scale(b){ ic.Scale = b; ic.Init(); } </script> <br /> <br /> <div> <input name="" type="button" value=" 增肥 " onclick="Size(500,400)" /> <input name="" type="button" value=" 还原 " onclick="Size(300,400)" /> </div> <br /> <div> <input name="" type="button" value=" 换图 " onclick="Pic('2.jpg')" /> <input name="" type="button" value=" 还原 " onclick="Pic('1.jpg')" /> </div> <br /> <div> <input name="" type="button" value=" 透明 " onclick="Opacity(0)" /> <input name="" type="button" value=" 还原 " onclick="Opacity(50)" /> </div> <br /> <div> <input name="" type="button" value="使用比例" onclick="Scale(true)" /> <input name="" type="button" value="取消比例" onclick="Scale(false)" /> </div> <br /> <div> <input name="" type="button" value="生成图片" onclick="Create()" /> <br /> <img id="imgCreat" /> </div> <script> function Create(){ var p = ic.Url, x = ic.Drag.offsetLeft, y = ic.Drag.offsetTop, w = ic.Drag.offsetWidth, h = ic.Drag.offsetHeight, pw = ic.Width, ph = ic.Height; $("imgCreat").src = "/createServlet?p=" + p + "&x=" + x + "&y=" + y + "&w=" + w + "&h=" + h + "&pw=" + pw + "&ph=" + ph; } </script> </body> </html> |
|||
aa | struts1标签 | ||
Struts标记分为(5组) 二期的时候JSP里学习过标准标签库与自定义标签,它的原理是一个JAVA类代码实现的,通过页面的 <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>来导入相应的配置文件,使用别名prefix即可调用标签库设定的标记 Html struts-html.tld Bean struts-bean.tld Logic struts-logic.tld Tiles struts-tiles.tld Nested struts-nested.tld 红字为Struts中重要掌握的标签内容。一般JSP页面都导入红字相应的标签 接下来通过一个实例来说明HTML标记的使用(struts-HTML标签库) 表单 Html代码 1. <html:form action="reg.do" method="post"> <html:form action="reg.do" method="post"> 文本框 Html代码 1. 用户名 <html:text property="username"/> 用户名 <html:text property="username"/> 密码框 Html代码 1. 密码 <html:password property="userpass"/> 密码 <html:password property="userpass"/> Property属性值的名字,就是对应ActionForm类里的属性名字 单选 性别 属性名字必须一致,否则视为多个单选组 Html代码 1. <html:radio property="gender" value="0"/>男 2. <html:radio property="gender" value="1"/>女 <html:radio property="gender" value="0"/>男 <html:radio property="gender" value="1"/>女 复选 爱好 这里返回的是一个数组,一般为String[] Html代码 1. <html:multibox property="hobby" value="看书"/>看书 2. <html:multibox property="hobby" value="睡觉"/>睡觉 3. <html:multibox property="hobby" value="编程"/>编程 <html:multibox property="hobby" value="看书"/>看书 <html:multibox property="hobby" value="睡觉"/>睡觉 <html:multibox property="hobby" value="编程"/>编程 下拉 Java代码 1. LabelValueBean lvbean=new LabelValueBean(); 2. lvbean.setLabel(""+i); 3. lvbean.setValue(""+i); 4. list.add(lvbean); LabelValueBean lvbean=new LabelValueBean(); lvbean.setLabel(""+i); lvbean.setValue(""+i); list.add(lvbean); 年龄 (它比较特殊,必须用到集合对象才可以往标签里添加下拉数据,它是以LABLE与 VALUE存取) 在ActionForm里获取的也是它设置的VALUE值。 Html代码 1. <html:select property="age"> 2. <html:options collection="list" labelProperty="label" property="value"/> 3. </html:select> <html:select property="age"> <html:options collection="list" labelProperty="label" property="value"/> </html:select> 文本区 Html代码 1. 备注 2. <html:textarea property="memo" rows="5" cols="60"/> 备注 <html:textarea property="memo" rows="5" cols="60"/> 隐藏 提交 直接请求发送 清除 清空表单的内容 取消 也是和请求一样会向Action请求,但是方式不一样可以用这个方法来判断是否是取消请求 Html代码 1. <html:submit>提交</html:submit> or <html:submit value=”提交”/> 2. <html:reset>清除</html:reset> 3. <html:cancel>取消</html:cancel> <html:submit>提交</html:submit> or <html:submit value=”提交”/> <html:reset>清除</html:reset> <html:cancel>取消</html:cancel> Java代码 1. //判断是否点击了"取消"按钮 2. boolean flag=this.isCancelled(request); 3. if(flag){ //如果点击了"取消"按钮 4. return mapping.findForward("reg"); 5. //重定向到注册页(想用重定向必须在struts-config.xml中配置属性 6. //<forward name="reg" path="/reg.jsp" redirect="true" /> 7. } //判断是否点击了"取消"按钮 boolean flag=this.isCancelled(request); if(flag){ //如果点击了"取消"按钮 return mapping.findForward("reg"); //重定向到注册页(想用重定向必须在struts-config.xml中配置属性 //<forward name="reg" path="/reg.jsp" redirect="true" /> } 第二个知识点为:Struts中的文件上传 记得以前Servlet时文件上传也是要在Form中指定请求数据类型吧,这里也一样(指定为二进制数据) Html代码 1. <html:form action="upload.do" method="post" enctype="multipart/form-data"> <html:form action="upload.do" method="post" enctype="multipart/form-data"> 用到的标签为[文件框] Html代码 1. <html:file property="photo"/> <html:file property="photo"/> 它对应的ActionForm的类型为org.apache.struts.upload.FormFile; 另一点注意的是,如果该表单里有其他的文本框要提交的话,需要注意的是,它也是以二进制数据提交,所以在ActionForm里无法直接通过请求处理配置转换成中文,必须使用自定义方法强制转换,并且要注意,它转发给页面时的一般属性也会丢失。如页面一有一属性与一文件上传,提交后直接转发到另一页面并显示属性的值报错 转换中文方法为: Java代码 1. public String changeGbk(String str){ 2. String newstr = null; 3. try { 4. newstr = new String(str.getBytes("ISO8859-1"), "gb2312"); 5. } catch (UnsupportedEncodingException ex) { 6. } 7. return newstr; 8. } public String changeGbk(String str){ String newstr = null; try { newstr = new String(str.getBytes("ISO8859-1"), "gb2312"); } catch (UnsupportedEncodingException ex) { } return newstr; } 接下来再看Action是如何处理文件上传的,它有两种方法处理上传文件并保存到指定目录。 方法一: 输入流 Java代码 1. UploadActionForm uploadActionForm = (UploadActionForm) form; 2. //接收内容并且存盘(web\photos) 3. FormFile photo=uploadActionForm.getPhoto();//获得请求文件的内容FormFile 4. try { 5. InputStream in=photo.getInputStream();//通过上传文件对象获得输入流 6. String filename=photo.getFileName();//常用方法,获得上传文件的文件名 7. String path=servlet.getServletContext().getRealPath("photos"); 8. //通过servlet获得服务器上下文对象获取指定目录的绝对路径 9. 如:d:\regprj\Web\photos 10. String newfilename=path + File.separator + filename; 11. //拼装要创建的文件全路径及文件名File.separator方法会根据系统自动选择’/’or’\’ 12. 如:d:\regprj\Web\photos\updatefile.jpg 13. FileOutputStream out=new FileOutputStream(newfilename);//把路径给文件输入流对象 14. 15. byte[] array1=new byte[1024];//设置缓冲大小,单位:字节 16. int len; 17. while( (len=in.read(array1))>0 ){ 18. out.write(array1,0,len); 19. } 20. out.flush(); 21. out.close(); 22. in.close(); 23. photo.destroy();//销毁文件; 24. } catch (Exception ex) { 25. ex.printStackTrace(); 26. } UploadActionForm uploadActionForm = (UploadActionForm) form; //接收内容并且存盘(web\photos) FormFile photo=uploadActionForm.getPhoto();//获得请求文件的内容FormFile try { InputStream in=photo.getInputStream();//通过上传文件对象获得输入流 String filename=photo.getFileName();//常用方法,获得上传文件的文件名 String path=servlet.getServletContext().getRealPath("photos"); //通过servlet获得服务器上下文对象获取指定目录的绝对路径 如:d:\regprj\Web\photos String newfilename=path + File.separator + filename; //拼装要创建的文件全路径及文件名File.separator方法会根据系统自动选择’/’or’\’ 如:d:\regprj\Web\photos\updatefile.jpg FileOutputStream out=new FileOutputStream(newfilename);//把路径给文件输入流对象 byte[] array1=new byte[1024];//设置缓冲大小,单位:字节 int len; while( (len=in.read(array1))>0 ){ out.write(array1,0,len); } out.flush(); out.close(); in.close(); photo.destroy();//销毁文件; } catch (Exception ex) { ex.printStackTrace(); } 方法二: Java代码 1. UploadActionForm uploadActionForm = (UploadActionForm) form; 2. //接收内容并且存盘(web\photos) 3. FormFile photo=uploadActionForm.getPhoto();//获得请求文件的内容FormFile 4. try { 5. String filename=photo.getFileName(); 6. String path=servlet.getServletContext().getRealPath("photos"); 7. String newfilename=path + File.separator + filename; 8. FileOutputStream out=new FileOutputStream(newfilename); 9. out.write(photo.getFileData()); 10. out.flush(); 11. out.close(); 12. photo.destroy();//销毁文件; 13. } catch (Exception ex) { 14. ex.printStackTrace(); 15. } UploadActionForm uploadActionForm = (UploadActionForm) form; //接收内容并且存盘(web\photos) FormFile photo=uploadActionForm.getPhoto();//获得请求文件的内容FormFile try { String filename=photo.getFileName(); String path=servlet.getServletContext().getRealPath("photos"); String newfilename=path + File.separator + filename; FileOutputStream out=new FileOutputStream(newfilename); out.write(photo.getFileData()); out.flush(); out.close(); photo.destroy();//销毁文件; } catch (Exception ex) { ex.printStackTrace(); } 区别就是两个方法使用的读取源二进制文件的方式不同。以上为黄色代码部份。 第三个知识点为<h1>测试超链接及图像标记</h1> Html代码 1. <html:link href="index.jsp">回主页</html:link><br /> 2. <html:link forward="index">回主页</html:link> <html:link href="index.jsp">回主页</html:link><br /> <html:link forward="index">回主页</html:link> 在<form-beans>后添加以下配置 Xml代码 1. <global-forwards> 2. <forward name="index" path="/index.jsp" /> 3. </global-forwards> <global-forwards> <forward name="index" path="/index.jsp" /> </global-forwards> 两个黄红代码中要配合一起才起使用 在一般的表单提交后,存放范围已经需要配置如request session,所以当请求交给了Action时,转发到JSP页面的时候,request所附带了请求的数据,可以直接用<bean: write>标签直接读取。但对象二进制数据的请求就不可以了。。 例: Html代码 1. <bean:write scope="request" name="regActionForm" property="username"/> <bean:write scope="request" name="regActionForm" property="username"/> Scope为请求数据存储在哪个范围,name就是请求的表单名,如:<form-bean name="regActionForm"。。 Property就是指请求时表单的属性名啦 |