多文件上传

/多文件上传
	public ActionForward multipartFileUpload(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		//转换为自己的表单,这里只要经过了一个表单就可以 ,不管里面的内容
		MulForm form2 = (MulForm)form;
		//多文件上传,通过form来获得页面的input = file的元素
		//用一个Hashtable来接收,<String,FormFile> ----键是页面的<input type="file" name="key">里面的name属性
		Hashtable<String, FormFile> hashtable = form2.getMultipartRequestHandler().getFileElements();
		//因为我在struts-config.xml里面控制了上传文件的大小
		//当文件超过了大小的时候,hashtable里面是空的,所以在这里判断一下
		if(hashtable.size()==0){
			request.setAttribute("info", "文件太大了!");
		}else {
			//循环里面的file
			for (Entry<String, FormFile> entry : hashtable.entrySet()) {
				//如果是没有上传文件,是空的要判断一下,用名字的长度来判断
				if(entry.getValue().getFileName().length()!=0){
					//获得保存路径
					String fileName = entry.getValue().getFileName();
					String webPath = ConfigPath.getProp().getProperty(ConfigPath.propKey);
					String realPath = this.getServlet().getServletContext().getRealPath(webPath);
					String savePath = ConfigPath.getSavePath(fileName, realPath);
					//建立流的管道
					InputStream inStream = entry.getValue().getInputStream();
					OutputStream outStream = new FileOutputStream(savePath);
					//开始传
					int len = 0 ;
					byte[] b = new byte[1024];
					while ((len = inStream.read(b))!=-1) {
						outStream.write(b, 0, len);
					}
					outStream.close();
					inStream.close();
				}
			}
			request.setAttribute("info", "上传成功!");
		}
		
		return mapping.findForward("showInfo");
	}

================================

public class ConfigPath {
	public static final String propKey = "hwt.MultipartUpload.relativePath";
	private static Properties prop = null ;
	private ConfigPath(){}
	
	static{
		prop = new Properties();
		//配置文件要放在类文件目录下面
		InputStream inStream = ConfigPath.class.getResourceAsStream("/configPath.properties");
		try {
			prop.load(inStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//处理文件上传的目录和文件名
	public static String getSavePath(String fileName,String realPath){
		//把文件名改成唯一的文件名 用UUID
		UUID uuid = UUID.randomUUID();
		String extraName = fileName.substring(fileName.lastIndexOf("."));
		String uniqueFileName = uuid+extraName;
		
		//文件的存储目录
		Calendar calendar = new GregorianCalendar();
		//===注意这里的盘符啊,在java中有盘符的绝对路径的时候要\\,因为编译器不认识\ 要转移\\
		//==相对路径就用这个/
		String path = realPath+"\\"+calendar.get(Calendar.YEAR)+"\\"+calendar.get(Calendar.MONTH)+
						"\\"+calendar.get(Calendar.DATE);
		//不要忘了要创建不存在目录的时候
		File file = new File(path);
		if(!file.exists()){
			file.mkdirs();
		}
		return path+"\\"+uniqueFileName;
	}
	
	//返回配置文件
	public static Properties getProp(){
		return prop;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值