老师说struts2文件上传而已,你看下面。
1.文件上传的页面upload.jsp。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%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"> </head> <body> <form action="user_test" method="post" enctype="multipart/form-data"> 文件:<input type="file" name="file"/> <br/> <input type="submit" value="submit"> </form> </body></html>
public class UserAction extends ActionSupport { /**文件上传相关属性**/private File file;//前台表单名字需叫fileprivate String fileFileName;private String fileContentType; //setter and getter 此处省略了 //上传的主要方法 @SuppressWarnings("deprecation")protected boolean upload(){boolean flag = false;InputStream is = null;OutputStream os = null;try{ is = new FileInputStream(file);String root = ServletActionContext.getRequest().getRealPath("/upload");//文件保存的路径File destFile = new File(root,this.getFileFileName());os = new FileOutputStream(destFile);byte[] buffer = new byte[400];int length =0;while((length = is.read(buffer))>0){os.write(buffer,0,length);}flag = true;}catch(Exception ex){flag = false;}finally{try {is.close();os.close();} catch (IOException e) {//do nothing}}return flag;}}/***前台表单提交到这里*/public String test(){if(upload()){successPath = "/upload/uploadresult.jsp";return SUCCESS;}else{ successPath = "/upload/uploadtest.jsp";return SUCCESS;}}<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%@taglib prefix="s" uri="/struts-tags"%><!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"> </head> <body> <img src="<%=request.getContextPath() %>/upload/<s:property value="fileFileName"/>" /> </body></html>