现如今许多web项目都设计到Flash头像上传,这套代码是我用过许多次的效果特别好,jsp部分可以结合页面的形式是弹框还是整个页面都行,只需把这段代码加进去,Java部分我的这个例子是springmvc的,大家可以结合自己的框架和命名对代码相应的地方进行改动。
1:jsp页面
<!--头像-->
<p id="swfContainer">
本组件需要安装Flash Player后才可使用,请从<a href="https://get.adobe.com/cn/flashplayer/?no_redirect" target="_blank">这里</a>下载安装。
</p>
<button type="button" id="upload" style="display:none;margin-top:8px;">swf外定义的上传按钮,点击可执行上传保存操作</button>
</div>
<script type="text/javascript" src="<%=path%>/resources/js/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="<%=path%>/resources/js/swfobject.js"></script>
<script type="text/javascript" src="<%=path%>/resources/js/fullAvatarEditor.js"></script>
<script type="text/javascript">
swfobject.addDomLoadEvent(function() {
//以下两行代码正式环境下请删除
var swf = new fullAvatarEditor("<%=path%>/resources/swf/fullAvatarEditor.swf", "<%=path%>/resources/swf/expressInstall.swf", "swfContainer", {
id: 'swf',
upload_url: '<%=path%>/userInfo/upload.htm?userid=${sessionScope.user.userId}&username=${sessionScope.user.userName}', //上传接口
method: 'post', //传递到上传接口中的查询参数的提交方式。更改该值时,请注意更改上传接口中的查询参数的接收方式
src_upload: 0, //是否上传原图片的选项,有以下值: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("头像上传成功!");
window.location.replace("${ctx}/userInfo/front_main_2.htm");
//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("头像上传成功!");
window.location.replace("${ctx}/userInfo/front_main_2.htm");
//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>
2java后台
/**
* 头像上传
* @param request
* @param response
* @return
* @throws IOException
* @throws FileUploadException
*/
@RequestMapping(value="/upload.htm")
public void upload(HttpServletRequest request, HttpServletResponse response) throws IOException, FileUploadException {
String contentType = request.getContentType();
PrintWriter out = response.getWriter();
if ( contentType.indexOf("multipart/form-data") >= 0 ){
Result result = new Result();
result.avatarUrls = new ArrayList<String>();
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 < 3; i++ ){
randomCode += Integer.toString(random.nextInt(36), 36);
}
fileName = fileName + randomCode;
//基于原图的初始化参数
String initParams = "";
BufferedInputStream inputStream;
BufferedOutputStream outputStream;
//遍历表单域
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();
}else if (isSourcePic || fieldName.startsWith("__avatar")){//如果是原始图片 file 域的名称或者以默认的头像域名称的部分“__avatar”打头(默认的头像域名称:__avatar1,2,3...,可在插件配置参数中自定义,参数名:avatar_field_names)
String virtualPath = File.separator+"upload"+File.separator+"img" + avatarNumber + "_" + fileName + ".jpg";//原始图片(默认的 file 域的名称是__source,可在插件配置参数中自定义。参数名:src_field_name)。
String virtualPath1 = "/upload/img" + avatarNumber + "_" + fileName + ".jpg";//原始图片(默认的 file 域的名称是__source,可在插件配置参数中自定义。参数名:src_field_name)。
if( isSourcePic){
String sourceFileName = fileItem.getName(); //文件名,如果是本地或网络图片为原始文件名、如果是摄像头拍照则为 *FromWebcam.jpg
String sourceExtendName = sourceFileName.substring(sourceFileName.lastIndexOf('.') + 1);//原始文件的扩展名(不包含“.”)
result.sourceUrl = virtualPath = String.format(File.separator+"upload"+File.separator+"img_%s.%s", fileName, sourceExtendName);
}else{//头像图片(默认的 file 域的名称:__avatar1,2,3...,可在插件配置参数中自定义,参数名:avatar_field_names)。
result.avatarUrls.add(virtualPath1);
avatarNumber++;
}
inputStream = new BufferedInputStream(fileItem.openStream());
outputStream = new BufferedOutputStream(new FileOutputStream(request.getRealPath("") + virtualPath));
Streams.copy(inputStream, outputStream, true);
inputStream.close();
outputStream.flush();
outputStream.close();
}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!";
List<String> photos = result.avatarUrls;
String photo="";
for(int i=0;i<photos.size();i++){
if(i<photos.size()-1){
photo=photo+photos.get(i)+",";}
else{
photo=photo+photos.get(i);
}
}
UserInfo userInfo=userInfoService.getUserInfo(Integer.parseInt(result.userid ));
userInfo.setPhoto(photo);
userInfoService.user_update(userInfo);
//将修改后的用户信息存入session
request.getSession().setAttribute("user", userInfo);
request.getSession().setAttribute("navigationphoto", photos.get(0));
//返回图片的保存结果(返回内容为json字符串,可自行构造,该处使用fastjson构造)
out.println(JSON.toJSONString(result));
}
}