uploadInput页面:
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>上传照片</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <link href="swfupload/default.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="/tiantian/swfupload/swfupload.js"></script> <script type="text/javascript" src="/tiantian/swfupload/handlers.js"></script> <script type="text/javascript"> var swfu; window.onload = function () { swfu = new SWFUpload({ // Backend Settings upload_url: "/tiantian/picture/upload",//上传到哪个地址 post_params: {"albumId": "${album.id}"},//传过去的参数 // File Upload Settings file_size_limit : "20 MB", // 2MB file_types : "*.jpg;*.jpeg;*.gif", file_types_description : "JPG Images", file_upload_limit : 0, // Event Handler Settings - these functions as defined in Handlers.js // The handlers are not part of SWFUpload but are part of my website and control how // my website reacts to the SWFUpload events. swfupload_preload_handler : preLoad, swfupload_load_failed_handler : loadFailed, file_queue_error_handler : fileQueueError, file_dialog_complete_handler : fileDialogComplete, upload_progress_handler : uploadProgress, upload_error_handler : uploadError, upload_success_handler : uploadSuccess, upload_complete_handler : uploadComplete, // Button Settings button_image_url : "/tiantian/images/swfupload/SmallSpyGlassWithTransperancy_17x18.png", button_placeholder_id : "spanButtonPlaceholder", button_width: 180, button_height: 18, button_text : '<span class="button">Select Images <span class="buttonSmall">(2 MB Max)</span></span>', button_text_style : '.button { font-family: Helvetica, Arial, sans-serif; font-size: 12pt; } .buttonSmall { font-size: 10pt; }', button_text_top_padding: 0, button_text_left_padding: 18, button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT, button_cursor: SWFUpload.CURSOR.HAND, // Flash Settings flash_url : "/tiantian/swfupload/swfupload.swf", flash9_url : "/tiantian/swfupload/swfupload_fp9.swf", custom_settings : { upload_target : "divFileProgressContainer" }, //Image Resize:no, // Debug Settings debug: false }); }; </script> <style type="text/css"> #tophead { text-align:left; padding-left:10px; margin-top:10px; } </style> </head> <body> <div id="tophead"> <a href="picture/index">返回相册首页</a> </div> <div id="content" style="text-align: left"> <h2>${album.name}</h2> <p>upload Images to ${album.name}</p> <form> <div style="width: 180px; height: 18px; border: solid 1px #7FAAFF; background-color: #C5D9FF; padding: 2px;"> <span id="spanButtonPlaceholder"></span> </div> </form> <div id="divFileProgressContainer" style="height: 75px;"></div> <div id="thumbnails"></div> </div> </body> </html>
上传页面用到的handler.js文件的内容:
function preLoad() { if (!this.support.loading) { alert("You need the Flash Player 9.028 or above to use SWFUpload."); return false; } } function loadFailed() { alert("Something went wrong while loading SWFUpload. If this were a real application we'd clean up and then give you an alternative"); } function fileQueueError(file, errorCode, message) { try { var imageName = "error.gif"; var errorName = ""; if (errorCode === SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED) { errorName = "You have attempted to queue too many files."; } if (errorName !== "") { alert(errorName); return; } switch (errorCode) { case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: imageName = "zerobyte.gif"; break; case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: imageName = "toobig.gif"; break; case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE: default: alert(message); break; } addImage("images/" + imageName); } catch (ex) { this.debug(ex); } } function fileDialogComplete(numFilesSelected, numFilesQueued) { try { if (numFilesQueued > 0) { this.startResizedUpload(this.getFile(0).ID, 100, 100, SWFUpload.RESIZE_ENCODING.JPEG, 100); } } catch (ex) { this.debug(ex); } } function uploadProgress(file, bytesLoaded) { try { var percent = Math.ceil((bytesLoaded / file.size) * 100); var progress = new FileProgress(file, this.customSettings.upload_target); progress.setProgress(percent); progress.setStatus("Uploading..."); progress.toggleCancel(true, this); } catch (ex) { this.debug(ex); } } function uploadSuccess(file, serverData) { try { var progress = new FileProgress(file, this.customSettings.upload_target); if (serverData.substring(0, 7) === "FILEID:") { //把上传的照片的缩略图在页面上进行显示 addImage("picture/thumbnail/" + serverData.substring(7)); // alert(serverData.substring(7)+"hello"); progress.setStatus("Upload Complete."); progress.toggleCancel(false); } else { addImage("images/swfupload/error.gif"); progress.setStatus("Error."); progress.toggleCancel(false); alert(serverData); } } catch (ex) { this.debug(ex); } } function uploadComplete(file) { try { /* I want the next upload to continue automatically so I'll call startUpload here */ if (this.getStats().files_queued > 0) { this.startResizedUpload(this.getFile(0).ID, 500, 500, SWFUpload.RESIZE_ENCODING.JPEG, 500); } else { var progress = new FileProgress(file, this.customSettings.upload_target); progress.setComplete(); progress.setStatus("All images received."); progress.toggleCancel(false); } } catch (ex) { this.debug(ex); } } function uploadError(file, errorCode, message) { var imageName = "error.gif"; var progress; try { switch (errorCode) { case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED: try { progress = new FileProgress(file, this.customSettings.upload_target); progress.setCancelled(); progress.setStatus("Cancelled"); progress.toggleCancel(false); } catch (ex1) { this.debug(ex1); } break; case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED: try { progress = new FileProgress(file, this.customSettings.upload_target); progress.setCancelled(); progress.setStatus("Stopped"); progress.toggleCancel(true); } catch (ex2) { this.debug(ex2); } case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: imageName = "uploadlimit.gif"; break; default: alert(message); break; } addImage("images/" + imageName); } catch (ex3) { this.debug(ex3); } } function addImage(src) { var newImg = document.createElement("img"); newImg.style.margin = "5px"; document.getElementById("thumbnails").appendChild(newImg); if (newImg.filters) { try { newImg.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 0; } catch (e) { // If it is not set initially, the browser will throw an error. This will set it if it is not set yet. newImg.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + 0 + ')'; } } else { newImg.style.opacity = 0; } newImg.onload = function () { fadeIn(newImg, 0); }; newImg.src = src; } function fadeIn(element, opacity) { var reduceOpacityBy = 5; var rate = 30; // 15 fps if (opacity < 100) { opacity += reduceOpacityBy; if (opacity > 100) { opacity = 100; } if (element.filters) { try { element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity; } catch (e) { // If it is not set initially, the browser will throw an error. This will set it if it is not set yet. element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity + ')'; } } else { element.style.opacity = opacity / 100; } } if (opacity < 100) { setTimeout(function () { fadeIn(element, opacity); }, rate); } } /* ****************************************** * FileProgress Object * Control object for displaying file info * ****************************************** */ function FileProgress(file, targetID) { this.fileProgressID = "divFileProgress"; this.fileProgressWrapper = document.getElementById(this.fileProgressID); if (!this.fileProgressWrapper) { this.fileProgressWrapper = document.createElement("div"); this.fileProgressWrapper.className = "progressWrapper"; this.fileProgressWrapper.id = this.fileProgressID; this.fileProgressElement = document.createElement("div"); this.fileProgressElement.className = "progressContainer"; var progressCancel = document.createElement("a"); progressCancel.className = "progressCancel"; progressCancel.href = "#"; progressCancel.style.visibility = "hidden"; progressCancel.appendChild(document.createTextNode(" ")); var progressText = document.createElement("div"); progressText.className = "progressName"; progressText.appendChild(document.createTextNode(file.name)); var progressBar = document.createElement("div"); progressBar.className = "progressBarInProgress"; var progressStatus = document.createElement("div"); progressStatus.className = "progressBarStatus"; progressStatus.innerHTML = " "; this.fileProgressElement.appendChild(progressCancel); this.fileProgressElement.appendChild(progressText); this.fileProgressElement.appendChild(progressStatus); this.fileProgressElement.appendChild(progressBar); this.fileProgressWrapper.appendChild(this.fileProgressElement); document.getElementById(targetID).appendChild(this.fileProgressWrapper); fadeIn(this.fileProgressWrapper, 0); } else { this.fileProgressElement = this.fileProgressWrapper.firstChild; this.fileProgressElement.childNodes[1].firstChild.nodeValue = file.name; } this.height = this.fileProgressWrapper.offsetHeight; } FileProgress.prototype.setProgress = function (percentage) { this.fileProgressElement.className = "progressContainer green"; this.fileProgressElement.childNodes[3].className = "progressBarInProgress"; this.fileProgressElement.childNodes[3].style.width = percentage + "%"; }; FileProgress.prototype.setComplete = function () { this.fileProgressElement.className = "progressContainer blue"; this.fileProgressElement.childNodes[3].className = "progressBarComplete"; this.fileProgressElement.childNodes[3].style.width = ""; }; FileProgress.prototype.setError = function () { this.fileProgressElement.className = "progressContainer red"; this.fileProgressElement.childNodes[3].className = "progressBarError"; this.fileProgressElement.childNodes[3].style.width = ""; }; FileProgress.prototype.setCancelled = function () { this.fileProgressElement.className = "progressContainer"; this.fileProgressElement.childNodes[3].className = "progressBarError"; this.fileProgressElement.childNodes[3].style.width = ""; }; FileProgress.prototype.setStatus = function (status) { this.fileProgressElement.childNodes[2].innerHTML = status; }; FileProgress.prototype.toggleCancel = function (show, swfuploadInstance) { this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden"; if (swfuploadInstance) { var fileID = this.fileProgressID; this.fileProgressElement.childNodes[0].onclick = function () { swfuploadInstance.cancelUpload(fileID); return false; }; } };
后台进行处理的struts2 Action代码:
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Date; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import org.apache.struts2.interceptor.RequestAware; import org.apache.struts2.interceptor.SessionAware; import com.opensymphony.xwork2.ActionSupport; import com.tiantian.tiantian.model.Album; import com.tiantian.tiantian.model.Picture; import com.tiantian.tiantian.model.User; import com.tiantian.tiantian.service.AlbumService; import com.tiantian.tiantian.service.PictureService; import com.tiantian.tiantian.util.ImageSizer; import com.tiantian.tiantian.util.Pager; import com.tiantian.tiantian.util.Util; public class PictureAction extends ActionSupport implements RequestAware,SessionAware { /** * */ private static final long serialVersionUID = 375280356930857300L; private PictureService pictureService; private AlbumService albumService; private int offset; private int maxResults = 20; private int totalRecords; private int totalPage; private Pager<Picture> pager; private Map<String, Object> request; private Map<String, Object> session; private List<Picture> pictures; private List<Album> albums; private int albumId; private Album album; //upload private File Filedata;//swfupload上传文件的默认名称 private String FiledataFileName; private String FiledataContentType; private String albumName; private int id; private Picture pic; private String username; public String execute() { User currentUser = (User)session.get("user"); ifFirstIn(currentUser);//如果用户是第一次访问,则给ta添加一个默认的相册 if (Util.isNull(username)) username = currentUser.getUsername(); albums = albumService.find(username); return SUCCESS; } private void ifFirstIn(User currentUser) { int size = albumService.find(currentUser.getUsername()).size(); if (size == 0) { Album album = new Album(); album.setOwner(currentUser); album.setName("我的相册"); albumService.add(album); } } public String myPictures() { if (albumId > 0) { album = albumService.findById(albumId); Object obj = request.get("pager.offset"); if (obj != null) offset = (Integer)obj; pager = pictureService.find(offset, maxResults, albumId); pictures = pager.getData(); totalRecords = pager.getTotalCount(); } return "myPictures"; } public String detail() { if (id > 0) { pic = pictureService.find(id); if (pic != null) pictures = pictureService.findAll(pic.getAlbum().getId()); } return "detail"; } public String uploadInput() { if (albumId > 0) album = albumService.findById(albumId); return "uploadInput"; } public void upload() throws IOException { // System.out.println("albumId = "+albumId); if (albumId > 0) { if (Filedata != null) { User currentUser = (User)session.get("user"); Album album = albumService.findById(albumId); String path = ServletActionContext.getServletContext().getRealPath("/images/pics/"+currentUser.getUsername()+"/"+album.getId()); File dir = new File(path); if (!dir.exists()) dir.mkdirs(); String fileName = geneFileName(FiledataFileName); File dest = new File(dir,fileName); Util.upload(Filedata, dest); String picName = FiledataFileName.substring(0,FiledataFileName.lastIndexOf(".")); boolean flag = album.getPictures().size()==0; Picture pic = new Picture(); pic.setUrl(fileName); pic.setName(picName); pic.setAlbum(album); pictureService.add(pic); album.getPictures().add(pic); int id = pic.getId(); if (flag) { int index = FiledataFileName.lastIndexOf("."); String extension = FiledataFileName.substring(index+1); String faceFileName = geneFileName(FiledataFileName); String faceUrl = currentUser.getUsername()+"/"+album.getId()+"/"+geneFileName(FiledataFileName); File dest1 = new File(dir,faceFileName); ImageSizer.resize(Filedata, dest1, 200, extension); album.setFaceUrl(faceUrl); } albumService.update(album); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.print("FILEID:"+id); } } } private String geneFileName(String fileName) { int index = fileName.lastIndexOf("."); String extension = fileName.substring(index); String prefix = Util.formatDate(new Date(), "yyyyMMddHHmmss"); String name = prefix + extension; return name; } public void addAlbum() throws IOException { HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); String outStr = "ok"; if (!Util.isNull(albumName)) { User owner = (User)session.get("user"); Album album = new Album(); album.setName(albumName); album.setOwner(owner); albumService.add(album); } else outStr = "操作失败!相册名称不能为空!"; out.write(outStr); out.flush(); out.close(); } public void delAlbum() throws IOException { HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); String outStr = "ok"; if (albumId > 0) { album = albumService.findById(albumId); albumService.del(albumId); String path = ServletActionContext.getServletContext().getRealPath("/images/pics")+"/"+album.getOwner().getUsername()+"/"+album.getId(); File dest = new File(path); if (dest.exists()) delDerectory(dest); } else { outStr = "操作错误,删除失败!"; } out.write(outStr); out.flush(); out.close(); } private void delDerectory(File dir) { File[] files = dir.listFiles(); for (File file:files) { file.delete(); } dir.delete(); } public String thumbnail() throws IOException { if (id > 0) { pic = pictureService.find(id); String path = ServletActionContext.getServletContext().getRealPath("/images/pics")+"/"+pic.getAlbum().getOwner().getUsername()+"/"+pic.getAlbum().getId()+"/"+pic.getUrl(); FileInputStream fis = new FileInputStream(path); int len = fis.available(); byte bytes[] = new byte[len]; fis.read(bytes); fis.close(); HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("image/jpeg"); OutputStream os = response.getOutputStream(); os.write(bytes); os.flush(); os.close(); } return NONE; } public void del() throws IOException { HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html"); PrintWriter out = response.getWriter(); String outStr = "ok"; if (id > 0) { Picture pic = pictureService.find(id); if (pic != null) { // pic.setAlbum(null); // pictureService.update(pic); pictureService.del(id); String path = ServletActionContext.getServletContext().getRealPath("/images/pics")+"/"+pic.getAlbum().getOwner().getUsername()+"/"+pic.getAlbum().getId()+"/"+pic.getUrl(); File dest = new File(path); if (dest.exists()) dest.delete(); } } else outStr = "操作错误,请求的内容不存在!"; out.write(outStr); out.flush(); out.close(); } public PictureService getPictureService() { return pictureService; } @Resource public void setPictureService(PictureService pictureService) { this.pictureService = pictureService; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public int getMaxResults() { return maxResults; } public void setMaxResults(int maxResults) { this.maxResults = maxResults; } public int getTotalRecords() { return totalRecords; } public void setTotalRecords(int totalRecords) { this.totalRecords = totalRecords; } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public Pager<Picture> getPager() { return pager; } public void setPager(Pager<Picture> pager) { this.pager = pager; } public Map<String, Object> getRequest() { return request; } public void setRequest(Map<String, Object> request) { this.request = request; } public List<Picture> getPictures() { return pictures; } public void setPictures(List<Picture> pictures) { this.pictures = pictures; } public List<Album> getAlbums() { return albums; } public void setAlbums(List<Album> albums) { this.albums = albums; } public Map<String, Object> getSession() { return session; } public void setSession(Map<String, Object> session) { this.session = session; } public AlbumService getAlbumService() { return albumService; } @Resource public void setAlbumService(AlbumService albumService) { this.albumService = albumService; } public int getAlbumId() { return albumId; } public void setAlbumId(int albumId) { this.albumId = albumId; } public File getFiledata() { return Filedata; } public void setFiledata(File filedata) { Filedata = filedata; } public String getFiledataFileName() { return FiledataFileName; } public void setFiledataFileName(String filedataFileName) { FiledataFileName = filedataFileName; } public String getFiledataContentType() { return FiledataContentType; } public void setFiledataContentType(String filedataContentType) { FiledataContentType = filedataContentType; } public String getAlbumName() { return albumName; } public void setAlbumName(String albumName) { this.albumName = albumName; } public Album getAlbum() { return album; } public void setAlbum(Album album) { this.album = album; } public int getId() { return id; } public void setId(String id) { if (!Util.isNull(id)) { try { this.id = Integer.parseInt(id); } catch (NumberFormatException e) { } } } public Picture getPic() { return pic; } public void setPic(Picture pic) { this.pic = pic; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }