现在的位置: 首页 > 综合 > 正文

Struts2.x实现上传

2018年07月13日 ⁄ 综合 ⁄ 共 1958字 ⁄ 字号 评论关闭

public class LoginAction extends BaseAction
{
	private static final long serialVersionUID = -4151618925872986515L;
	
	private UserService userService;
	
	private File file;//上传的文件
	
	/**
	 * 注册接口
	 */
	public void registerUser() throws Exception
	{

		String userImageDir = createDirForUserImage();
		
		//String dir = request.getSession().getServletContext().getRealPath("/");
		String imagePath = userImageDir+System.currentTimeMillis()+_email+"."+_format;//图片文件地址
		
		File saveFile = new File(imagePath);
		user.setImageUrl(imagePath);
		
		FileUtils.copyFile(file, saveFile);// 复制文件
	}
	private String createDirForUserImage()
	{
		String dir = "user_image\\";
		Calendar calendar = Calendar.getInstance();
		
		String year = String.valueOf(calendar.get(Calendar.YEAR));
		String month = String.valueOf(calendar.get(Calendar.MONTH)+1);
		String day = String.valueOf(calendar.get(Calendar.DATE));
		
		String year_dir = dir + year +"\\";
		String month_dir = year_dir + month + "\\";
		String day_dir = month_dir + day + "\\";
		
		File day_file = new File(day_dir);
		if (!(day_file.isDirectory()))
		{
			day_file.mkdirs();
		}
		
		return day_dir;
	}
}

<%@ 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>My JSP 'index.jsp' starting page</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">
	-->
  </head>
  
  <body>
    <form action="myFriendService/registerUser.action" method="post" enctype="multipart/form-data">
		<table>
			<tr>
				<td>标题</td>
				<td><input type="text" name="title"></td>		
			</tr>
			<tr>
				<td>文件</td>
				<td><input type="file" name="file"></td>
			</tr>
			<tr>
				<td><input type="submit" value="提交"></td>
				<td><input type="reset" value="重置"></td>
			</tr>
		</table>
	</form>
  </body>
</html>

【上篇】
【下篇】

抱歉!评论已关闭.