struts2 上传文件

 

1. 随即生成 路径的文件夹,属于共用方法

 

 

import java.io.File;

public class UploadUtil {
	public static String makeDirs(String storeDirectory, String fileName) {
		int hashCode = fileName.hashCode();
		int dir1 = hashCode&0xf;
		int dir2 = (hashCode&0xf0)>>4;
		
		String newPath = dir1+"/"+dir2;
		File directory = new File(storeDirectory,newPath);
		if(!directory.exists())
			directory.mkdirs();
		newPath=storeDirectory+directory.separator+dir1+directory.separator+dir2;
		return newPath;
	}
}


 

2 action 层

 

// 文件上传
	private File upload;

	private String uploadFileName;
	private String uploadContentType;
	private InputStream fileStream;
	private OutputStream out;


 

public String save(){  
		
		String storeDirectory=ServletActionContext.getServletContext().getRealPath("/file");
		try {
			 fileStream = new FileInputStream(upload);
			 String uri=UploadUtil.makeDirs(storeDirectory, uploadFileName);
			
			 File f=new File(uri);
			 if(f.exists()){
				 out=new FileOutputStream(uri+f.separator+uploadFileName);
			 }
			 
			 int len=-1;
			 byte[] b=new byte[1024];
			 while((len=fileStream.read(b))!=-1){
				 out.write(b, 0, len);
			 }
			 model.setImage(uri);
			 model.setImageurl(uploadFileName);
			 
			 hbase.save(model);
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(fileStream!=null)
				try {
					fileStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if(out!=null)
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		
		return SUCCESS;
		
	}


 3.jsp 页面 (upload  要与action 的 private File upload;  名字保持一致  )

 

	<tr>
		<td>
			图片:<input type="file" name="upload"/><br/>
		</td>
	</tr>


4. 上传文件 是sturts 的拦截器 功能, 自定拦截器或者 使用默认的只要 继承了 extends="struts-default"   即可。  

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值