Struts2的文件上传_自我学习

首先是JSP,使用S2标签

   <s:form action="/test/upload" enctype="multipart/form-data">
   		<s:file name="file"></s:file>
   		<s:submit></s:submit>
   </s:form>

 其次是处理的action

private String title;
	private String fileFileName;
	private File file;
	private String savePath;
	
	public String execute()
	{
		try {
			File file = new File(getSavePath());
			//首先判断该文件夹是否存在,若不存在则建立一个,这样就不需要手动建立文件夹了
			if(!file.exists())
			{				
				file.mkdirs();
			}
			FileOutputStream fs = new FileOutputStream(getSavePath()+"//"+getFileFileName());
			FileInputStream fi = new FileInputStream(getFile());
			byte[] b = new byte[1024];
			int len = 0;
			while((len = fi.read(b)) > 0)
			{
				fs.write(b, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "success";
	}
值得注意的是,struts2为文件上传封装了两个隐藏属性,文件名和文件类型,这两个属性在action中的表示为xxxFileName,xxxContentType,其中xxx是JSP中文件控件的名字,在写action的时候,要注意savepath的get方法内要这么写
               //返回上传文件的保存位置
		return ServletActionContext.getServletContext().getRealPath(""+savePath);
savePath是struts配置文件中定义的一个常量,为上传文件所存放的文件夹名称

猜你喜欢

转载自alexshaw.iteye.com/blog/1819010