一、所需jar包
二、index.jsp
其中jquery-1.4.2.min.js和jquery.form.js需要网上自己去下载
1 <%@ page language="java" import="java.util.*" pageEncoding="gbk"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme() + "://" 5 + request.getServerName() + ":" + request.getServerPort() 6 + path + "/"; 7 %> 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 9 <html> 10 <head> 11 <base href="<%=basePath%>"> 12 <mce:script type="text/javascript" src="<%=path%><!-- 13 /js/jquery-1.4.2.min.js"> 14 // --></mce:script> 15 <mce:script type="text/javascript" src="<%=path%><!-- 16 /js/jquery.form.js"> 17 // --></mce:script> 18 19 <mce:script type="text/javascript"><!-- 20 function uploadImage() { 21 $(document) 22 .ready( 23 function() { 24 var options = { 25 url : "<%=path%>/uploadFile.action", 26 type : "POST", 27 dataType : "script", 28 success : function(msg) { 29 if (msg.indexOf("#") > 0) { 30 var data = msg.split("#"); 31 $("#tipDiv").html(data[0]); 32 $("#showImage").html("<img src='<%=path%>/showImage.action?imageUrl="+data[1]+"'/>"); 33 } else { 34 $("#tipDiv").html(msg); 35 } 36 } 37 }; 38 $("#form2").ajaxSubmit(options); 39 return false; 40 }); 41 } 42 // --></mce:script> 43 </head> 44 <body> 45 <center> 46 <form id="form2" method="post" enctype="multipart/form-data"> 47 <table width="400" border="1" cellspacing="1" cellpadding="10"> 48 <tr> 49 <td height="25"> 50 浏览图片: 51 </td> 52 <td> 53 <input id="fileupload" name="fileupload" type="file" /> 54 <div id="tipDiv"></div> 55 </td> 56 </tr> 57 <tr> 58 <td colspan="2" align="center"> 59 <input type="button" class="right-button02" 60 onclick="uploadImage()" value="上传" /> 61 </td> 62 </tr> 63 </table> 64 </form> 65 <br> 66 图片预览 67 <div id="showImage"></div> 68 </center> 69 </body> 70 </html>
三、UploadUtilAction.java
1 package action; 2 import java.awt.Image; 3 import java.awt.image.RenderedImage; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.IOException; 7 import java.io.InputStream; 8 import java.io.OutputStream; 9 import java.io.PrintWriter; 10 import java.text.SimpleDateFormat; 11 import java.util.Date; 12 import java.util.Random; 13 import javax.imageio.ImageIO; 14 import javax.servlet.http.HttpServletResponse; 15 import org.apache.commons.io.FileUtils; 16 import org.apache.struts2.ServletActionContext; 17 import org.apache.struts2.interceptor.ServletResponseAware; 18 import util.UtilCommon; 19 import com.opensymphony.xwork2.ActionSupport; 20 public class UploadUtilAction extends ActionSupport implements 21 ServletResponseAware { 22 private File fileupload; // 和JSP中input标记name同名 23 private String imageUrl; 24 private String attachmentUrl; 25 private String fileRealName; 26 private HttpServletResponse response; 27 // Struts2拦截器获得的文件名,命名规则,File的名字+FileName 28 // 如此处为 'fileupload' + 'FileName' = 'fileuploadFileName' 29 private String fileuploadFileName; // 上传来的文件的名字 30 public String uploadFile() { 31 String extName = ""; // 保存文件拓展名 32 String newFileName = ""; // 保存新的文件名 33 String nowTimeStr = ""; // 保存当前时间 34 PrintWriter out = null; 35 SimpleDateFormat sDateFormat; 36 Random r = new Random(); 37 String savePath = ServletActionContext.getServletContext().getRealPath( 38 ""); // 获取项目根路径 39 savePath = savePath + "/file/"; 40 HttpServletResponse response = ServletActionContext.getResponse(); 41 response.setCharacterEncoding("gbk"); // 务必,防止返回文件名是乱码 42 // 生成随机文件名:当前年月日时分秒+五位随机数(为了在实际项目中防止文件同名而进行的处理) 43 int rannum = (int) (r.nextDouble() * (99999 - 10000 + 1)) + 10000; // 获取随机数 44 sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); // 时间格式化的格式 45 nowTimeStr = sDateFormat.format(new Date()); // 当前时间 46 // 获取拓展名 47 if (fileuploadFileName.lastIndexOf(".") >= 0) { 48 extName = fileuploadFileName.substring(fileuploadFileName 49 .lastIndexOf(".")); 50 } 51 try { 52 out = response.getWriter(); 53 newFileName = nowTimeStr + rannum + extName; // 文件重命名后的名字 54 String filePath = savePath + newFileName; 55 filePath = filePath.replace("//", "/"); 56 //检查上传的是否是图片 57 if (UtilCommon.checkIsImage(extName)) { 58 FileUtils.copyFile(fileupload, new File(filePath)); 59 out.print("<font color='red'>" + fileuploadFileName 60 + "上传成功!</font>#" + filePath + "#" + fileuploadFileName); 61 } else { 62 out.print("<font color='red'>上传的文件类型错误,请选择jpg,jpeg,png和gif格式的图片!</font>"); 63 } 64 out.flush(); 65 out.close(); 66 } catch (IOException e) { 67 e.printStackTrace(); 68 out.print("上传失败,出错啦!"); 69 } 70 return null; 71 } 72 public String showImage() throws Exception { 73 // 根据图片地址构造file对象 74 File file = new File(imageUrl); 75 InputStream is = new FileInputStream(file); 76 Image image = ImageIO.read(is);// 读图片 77 String imageType = imageUrl.substring(imageUrl.lastIndexOf(".") + 1); 78 RenderedImage img = (RenderedImage) image; 79 OutputStream out = response.getOutputStream(); 80 ImageIO.write(img, imageType, out); 81 out.flush(); 82 out.close(); 83 return null; 84 } 85 public File getFileupload() { 86 return fileupload; 87 } 88 public void setFileupload(File fileupload) { 89 this.fileupload = fileupload; 90 } 91 public String getImageUrl() { 92 return imageUrl; 93 } 94 public void setImageUrl(String imageUrl) { 95 this.imageUrl = imageUrl; 96 } 97 public String getAttachmentUrl() { 98 return attachmentUrl; 99 } 100 public void setAttachmentUrl(String attachmentUrl) { 101 this.attachmentUrl = attachmentUrl; 102 } 103 public String getFileRealName() { 104 return fileRealName; 105 } 106 public void setFileRealName(String fileRealName) { 107 this.fileRealName = fileRealName; 108 } 109 public void setServletResponse(HttpServletResponse response) { 110 this.response = response; 111 } 112 public String getFileuploadFileName() { 113 return fileuploadFileName; 114 } 115 public void setFileuploadFileName(String fileuploadFileName) { 116 this.fileuploadFileName = fileuploadFileName; 117 } 118 119 }
UtilCommon.java
1 package util; 2 import java.text.SimpleDateFormat; 3 import java.util.Date; 4 public class UtilCommon { 5 public static String getSerial(Date date, int index) { 6 long msel = date.getTime(); 7 SimpleDateFormat fm = new SimpleDateFormat("MMddyyyyHHmmssSS"); 8 msel += index; 9 date.setTime(msel); 10 String serials = fm.format(date); 11 return serials; 12 } 13 // 检查是否是图片格式 14 public static boolean checkIsImage(String imgStr) { 15 boolean flag = false; 16 if (imgStr != null) { 17 if (imgStr.equalsIgnoreCase(".gif") 18 || imgStr.equalsIgnoreCase(".jpg") 19 || imgStr.equalsIgnoreCase(".jpeg") 20 || imgStr.equalsIgnoreCase(".png")) { 21 flag = true; 22 } 23 } 24 return flag; 25 } 26 }
struts.xml
1 <?xml version="1.0" encoding="utf-8" ?> 2 <!DOCTYPE struts PUBLIC 3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 4 "http://struts.apache.org/dtds/struts-2.0.dtd"> 5 <struts> 6 <package name="struts2" namespace="/" extends="struts-default"> 7 <action name="*" class="action.UploadUtilAction" method="{1}"></action> 8 </package> 9 </struts>
web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 5 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 6 <display-name>struts 2.0</display-name> 7 <!-- 定义structs2的FilterDispatcher的Filter --> 8 <filter> 9 <!-- 定义核心Filter的名字 --> 10 <filter-name>struts2</filter-name> 11 <!-- 定义核心Filter的实现类 --> 12 <filter-class> 13 org.apache.struts2.dispatcher.FilterDispatcher 14 </filter-class> 15 </filter> 16 <filter-mapping> 17 <filter-name>struts2</filter-name> 18 <url-pattern>/*</url-pattern> 19 </filter-mapping> 20 <welcome-file-list> 21 <welcome-file>index.jsp</welcome-file> 22 </welcome-file-list> 23 </web-app>
运行效果