struts2+jquery之form插件实现异步上传图片并显示

一、所需jar包

二、index.jsp

其中jquery-1.4.2.min.js和jquery.form.js需要网上自己去下载

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <% 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%>"> <mce:script type="text/javascript" src="<%=path%><!-- /js/jquery-1.4.2.min.js"> // --></mce:script> <mce:script type="text/javascript" src="<%=path%><!-- /js/jquery.form.js"> // --></mce:script> <mce:script type="text/javascript"><!-- function uploadImage() { $(document) .ready( function() { var options = { url : "<%=path%>/uploadFile.action", type : "POST", dataType : "script", success : function(msg) { if (msg.indexOf("#") > 0) { var data = msg.split("#"); $("#tipDiv").html(data[0]); $("#showImage").html("<img src='<%=path%>/showImage.action?imageUrl="+data[1]+"'/>"); } else { $("#tipDiv").html(msg); } } }; $("#form2").ajaxSubmit(options); return false; }); } // --></mce:script> </head> <body> <center> <form id="form2" method="post" enctype="multipart/form-data"> <table width="400" border="1" cellspacing="1" cellpadding="10"> <tr> <td height="25"> 浏览图片: </td> <td> <input id="fileupload" name="fileupload" type="file" /> <div id="tipDiv"></div> </td> </tr> <tr> <td colspan="2" align="center"> <input type="button" class="right-button02" οnclick="uploadImage()" value="上传" /> </td> </tr> </table> </form> <br> 图片预览 <div id="showImage"></div> </center> </body> </html>

三、UploadUtilAction.java

package action; import java.awt.Image; import java.awt.image.RenderedImage; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.apache.struts2.ServletActionContext; import org.apache.struts2.interceptor.ServletResponseAware; import util.UtilCommon; import com.opensymphony.xwork2.ActionSupport; public class UploadUtilAction extends ActionSupport implements ServletResponseAware { private File fileupload; // 和JSP中input标记name同名 private String imageUrl; private String attachmentUrl; private String fileRealName; private HttpServletResponse response; // Struts2拦截器获得的文件名,命名规则,File的名字+FileName // 如此处为 'fileupload' + 'FileName' = 'fileuploadFileName' private String fileuploadFileName; // 上传来的文件的名字 public String uploadFile() { String extName = ""; // 保存文件拓展名 String newFileName = ""; // 保存新的文件名 String nowTimeStr = ""; // 保存当前时间 PrintWriter out = null; SimpleDateFormat sDateFormat; Random r = new Random(); String savePath = ServletActionContext.getServletContext().getRealPath( ""); // 获取项目根路径 savePath = savePath + "/file/"; HttpServletResponse response = ServletActionContext.getResponse(); response.setCharacterEncoding("gbk"); // 务必,防止返回文件名是乱码 // 生成随机文件名:当前年月日时分秒+五位随机数(为了在实际项目中防止文件同名而进行的处理) int rannum = (int) (r.nextDouble() * (99999 - 10000 + 1)) + 10000; // 获取随机数 sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); // 时间格式化的格式 nowTimeStr = sDateFormat.format(new Date()); // 当前时间 // 获取拓展名 if (fileuploadFileName.lastIndexOf(".") >= 0) { extName = fileuploadFileName.substring(fileuploadFileName .lastIndexOf(".")); } try { out = response.getWriter(); newFileName = nowTimeStr + rannum + extName; // 文件重命名后的名字 String filePath = savePath + newFileName; filePath = filePath.replace("//", "/"); //检查上传的是否是图片 if (UtilCommon.checkIsImage(extName)) { FileUtils.copyFile(fileupload, new File(filePath)); out.print("<font color='red'>" + fileuploadFileName + "上传成功!</font>#" + filePath + "#" + fileuploadFileName); } else { out.print("<font color='red'>上传的文件类型错误,请选择jpg,jpeg,png和gif格式的图片!</font>"); } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); out.print("上传失败,出错啦!"); } return null; } public String showImage() throws Exception { // 根据图片地址构造file对象 File file = new File(imageUrl); InputStream is = new FileInputStream(file); Image image = ImageIO.read(is);// 读图片 String imageType = imageUrl.substring(imageUrl.lastIndexOf(".") + 1); RenderedImage img = (RenderedImage) image; OutputStream out = response.getOutputStream(); ImageIO.write(img, imageType, out); out.flush(); out.close(); return null; } public File getFileupload() { return fileupload; } public void setFileupload(File fileupload) { this.fileupload = fileupload; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getAttachmentUrl() { return attachmentUrl; } public void setAttachmentUrl(String attachmentUrl) { this.attachmentUrl = attachmentUrl; } public String getFileRealName() { return fileRealName; } public void setFileRealName(String fileRealName) { this.fileRealName = fileRealName; } public void setServletResponse(HttpServletResponse response) { this.response = response; } public String getFileuploadFileName() { return fileuploadFileName; } public void setFileuploadFileName(String fileuploadFileName) { this.fileuploadFileName = fileuploadFileName; } }

UtilCommon.java

package util; import java.text.SimpleDateFormat; import java.util.Date; public class UtilCommon { public static String getSerial(Date date, int index) { long msel = date.getTime(); SimpleDateFormat fm = new SimpleDateFormat("MMddyyyyHHmmssSS"); msel += index; date.setTime(msel); String serials = fm.format(date); return serials; } // 检查是否是图片格式 public static boolean checkIsImage(String imgStr) { boolean flag = false; if (imgStr != null) { if (imgStr.equalsIgnoreCase(".gif") || imgStr.equalsIgnoreCase(".jpg") || imgStr.equalsIgnoreCase(".jpeg") || imgStr.equalsIgnoreCase(".png")) { flag = true; } } return flag; } }

四、struts.xml

<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="struts2" namespace="/" extends="struts-default"> <action name="*" class="action.UploadUtilAction" method="{1}"></action> </package> </struts>

五、web.xml

<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>struts 2.0</display-name> <!-- 定义structs2的FilterDispatcher的Filter --> <filter> <!-- 定义核心Filter的名字 --> <filter-name>struts2</filter-name> <!-- 定义核心Filter的实现类 --> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>

六、工程图

七、运行效果

源码可以去http://download.csdn.net/source/3351355 下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值