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" 即可。