今天给大家介绍一款强大的Flash头像编辑上传插件。富头像上传编辑,支持本地,预览和视频拍照和网络加载的flash头像编辑插件,可缩放,裁剪,定义和调色等。说了这么多,咱们先看看效果怎样
首先下载插件地址
http://pan.baidu.com/s/1qWBhTne
加压文件将以下js引入工程
swfobject.js
fullAvatarEditor.js
在web项目中添加以下两个flash文件
FullAvatarEditor.swf'和expressInstall.swf
工程基本结构
<%@ pagelanguage="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE htmlPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <metahttp-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Inserttitle here</title> </head> <p id="swfContainer"> 本组件需要安装Flash Player后才可使用,请从<ahref="http://dl.pconline.com.cn/html_2/1/114/id=8122&pn=0.html"target="_blank">这里</a>下载安装。 </p> <buttontype="button" id="upload"style="display:none;margin-top:8px;">点击上传</button> <scripttype="text/javascript"src="http://www.sucaihuo.com/Public/js/other/jquery.js"></script> <scripttype="text/javascript"src="${pageContext.request.contextPath}/scripts/swfobject.js"></script> <scripttype="text/javascript"src="${pageContext.request.contextPath}/scripts/fullAvatarEditor.js"></script> <scripttype="text/javascript"> swfobject.addDomLoadEvent(function() { //以下两行代码正式环境下请删除 if(location.href.indexOf('http://') == -1) alert('请于WEB服务器环境中查看、测试!\n\n既 http://*/simpleDemo.html\n\n而不是本地路径 file:///*/simpleDemo.html的方式'); var swf = newfullAvatarEditor("fullAvatarEditor.swf","expressInstall.swf", "swfContainer", { id: 'swf', upload_url:'/tewst/testServlet?userid=999&username=looselive', //上传接口,这里为后台对应servlet方法 method: 'post', //传递到上传接口中的查询参数的提交方式。更改该值时,请注意更改上传接口中的查询参数的接收方式 src_upload: 2,//是否上传原图片的选项,有以下值:0-不上传;1-上传;2-显示复选框由用户选择 avatar_box_border_width: 0, avatar_sizes:'100*100|50*50|32*32', avatar_sizes_desc: '100*100像素|50*50像素|32*32像素' }, function(msg) { switch (msg.code) { case 1 : // alert("页面成功加载了组件!"); break; case 2 : // alert("已成功加载图片到编辑面板。"); document.getElementById("upload").style.display ="inline"; break; case 3 : if (msg.type == 0) { alert("摄像头已准备就绪且用户已允许使用。"); } else if (msg.type == 1) { alert("摄像头已准备就绪但用户未允许使用!"); } else { alert("摄像头被占用!"); } break; case 5 : if (msg.type == 0) { if(msg.content.sourceUrl) { alert("原图已成功保存至服务器,url为:\n" +msg.content.sourceUrl + "\n\n" + "头像已成功保存至服务器,url为:\n" +msg.content.avatarUrls.join("\n\n") + "\n\n传递的userid=" + msg.content.userid + "&username=" +msg.content.username); } else { alert("头像已成功保存至服务器,url为:\n" +msg.content.avatarUrls.join("\n\n") + "\n\n传递的userid=" + msg.content.userid + "&username=" +msg.content.username); } } break; } } ); document.getElementById("upload").onclick = function() { swf.call("upload"); }; }); </script> </html>
创建一个处理图片action类
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.FileItemStream; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.util.Streams; /** 后台图片处理操作类 **/ public class actionspost extends HttpServlet { /** * @Fields serialVersionUID : */ private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { getimage(request, response); } catch (FileUploadException e) { e.printStackTrace(); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } /** * 图片保存类 * * @param request * @param response * @throws UnsupportedEncodingException * @throws FileUploadException * @throws IOException */ public void getimage(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, FileUploadException, IOException { String contentType = request.getContentType(); if (contentType.indexOf("multipart/form-data") >= 0) { ResultMessage result = new ResultMessage(); result.avatarUrls = new ArrayList(); result.success = false; result.msg = "Failure!"; String userid; String username; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); FileItemIterator fileItems = upload.getItemIterator(request); // 定义一个变量用以储存当前头像的序号 int avatarNumber = 1; // 取服务器时间+8位随机码作为部分文件名,确保文件名无重复。 SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyyMMddHHmmssS"); String fileName = simpleDateFormat.format(new Date()); Random random = new Random(); String randomCode = ""; for (int i = 0; i < 8; i++) { randomCode += Integer.toString(random.nextInt(36), 36); } fileName = fileName + randomCode; // 基于原图的初始化参数 String initParams = ""; BufferedInputStream inputStream = null; BufferedOutputStream outputStream = null; // 遍历表单域 while (fileItems.hasNext()) { FileItemStream fileItem = fileItems.next(); String fieldName = fileItem.getFieldName(); // 是否是原始图片 file 域的名称(默认的 file // 域的名称是__source,可在插件配置参数中自定义。参数名:src_field_name) Boolean isSourcePic = fieldName.equals("__source"); // 当前头像基于原图的初始化参数(只有上传原图时才会发送该数据,且发送的方式为POST),用于修改头像时保证界面的视图跟保存头像时一致,提升用户体验度。 // 修改头像时设置默认加载的原图url为当前原图url+该参数即可,可直接附加到原图url中储存,不影响图片呈现。 if (fieldName.equals("__initParams")) { inputStream = new BufferedInputStream(fileItem.openStream()); byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes); initParams = new String(bytes, "UTF-8"); inputStream.close(); } // 如果是原始图片 file // 域的名称或者以默认的头像域名称的部分“__avatar”打头(默认的头像域名称:__avatar1,2,3...,可在插件配置参数中自定义,参数名:avatar_field_names) else if (isSourcePic || fieldName.startsWith("__avatar")) { String virtualPath = "/upload/jsp_avatar" + avatarNumber + "_" + fileName + ".jpg"; // 原始图片(默认的 file // 域的名称是__source,可在插件配置参数中自定义。参数名:src_field_name)。 if (isSourcePic) { // 文件名,如果是本地或网络图片为原始文件名、如果是摄像头拍照则为 *FromWebcam.jpg String sourceFileName = fileItem.getName(); // 原始文件的扩展名(不包含“.”) String sourceExtendName = sourceFileName .substring(sourceFileName.lastIndexOf('.') + 1); result.sourceUrl = virtualPath = String.format( "/upload/jsp_source_%s.%s", fileName, sourceExtendName); } // 头像图片(默认的 file // 域的名称:__avatar1,2,3...,可在插件配置参数中自定义,参数名:avatar_field_names)。 else { result.avatarUrls.add(virtualPath); avatarNumber++; } try { inputStream = new BufferedInputStream( fileItem.openStream()); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { outputStream = new BufferedOutputStream( new FileOutputStream(getServletContext() .getRealPath("/") + virtualPath.replace("/", "\\"))); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { Streams.copy(inputStream, outputStream, true); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { outputStream.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { outputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { // 注释① // upload_url中传递的查询参数,如果定义的method为post请使用下面的代码,否则请删除或注释下面的代码块并使用注释②的代码 inputStream = new BufferedInputStream(fileItem.openStream()); byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes); inputStream.close(); if (fieldName.equals("userid")) { result.userid = new String(bytes, "UTF-8"); } else if (fieldName.equals("username")) { result.username = new String(bytes, "UTF-8"); } } } // 注释② upload_url中传递的查询参数,如果定义的method为get请使用下面注释的代码 /* * result.userid = request.getParameter("userid"); result.username = * request.getParameter("username"); */ if (result.sourceUrl != null) { result.sourceUrl += initParams; } result.success = true; result.msg = "Success!"; /* * To Do...可在此处处理储存事项 */ // 返回图片的保存结果(返回内容为json字符串,可自行构造,该处使用fastjson构造) // JSON.toJSONString(result); } } }
消息处理类ResultMessage
import java.io.Serializable; import java.util.ArrayList; public class ResultMessage implements Serializable { /** * @Fields serialVersionUID */ private static final long serialVersionUID = 1L; /** * 表示图片是否已上传成功。 */ public Boolean success; public String userid; public String username; /** * 自定义的附加消息。 */ public String msg; /** * 表示原始图片的保存地址。 */ public String sourceUrl; /** * 表示所有头像图片的保存地址,该变量为一个数组。 */ public ArrayList avatarUrls; }
说明
newfullAvatarEditor(['*/FullAvatarEditor.swf',]['*/expressInstall.swf',] swfContainerID [,height] [,width], flashvars,[callback]);
*/FullAvatarEditor.swf 插件主swf文件的路径,文件名必须是FullAvatarEditor.swf */expressInstall.swf expressInstall.swf文件的路径,文件名必须是expressInstall.swf swfContainerID 用以包裹Flash的HTML元素的ID。 height Flash的高度,默认为600。 width Flash的宽度,默认为630。 flashvars 将要传递到flash 的 key/value 参数,请参见 配置参数。 callback flash执行某些操作时的回调函数,请参见回调函数。
小结: 插件兼容的浏览器挺多的,api操作简单。不错的。有用到的同学希望可以帮到。