为什么我用Struts 2的fileupload组件上传文件成功后,上传的文件只保存在Tomcat的upload文件夹下面,而我的项目中upload文件夹并没有那个上传的文件,而且Tomcat我将它关闭后再重新开启,那个上传的文件也不见了。请问怎么才能让文件保存在我的项目根目录upload文件夹下呢。
Action中的核心代码:
- Java code
public String execute() throws Exception { //文件保存的文件夹 String path = ServletActionContext.getRequest().getRealPath("/upload"); //得到上传的文件对象 InputStream is = new FileInputStream(file); System.out.println("fileFileName:"+getFileFileName());//打印获取到的文件名称 System.out.println("fileContentType:"+getFileContentType());//打印获取到的文件类型 File rootPath = new File(path,getFileFileName());//封装文件路径和文件名 OutputStream os = new FileOutputStream(rootPath);//将文件输出到指定的文件夹 byte[] buffer = new byte[400];//新建字节对象 int length = 0; //如果长度不为-1,则循环的读取文件对象 while(-1 != (length = is.read(buffer))){ os.write(buffer, 0, length); } //读写玩文件后,将输入输出流关闭 is.close(); os.close(); return Action.SUCCESS; }
------解决方案--------------------
[code=Java][/code]
public void upload(){
try {
//创建文件流,用来读写
//1. 创建写入对象
FileOutputStream out = new FileOutputStream(new File(ServletActionContext.getServletContext().
getRealPath("/")+"/upload/"+getImageFileName()));
System.out.println("--->:"+getImage());
//2. 创建读取对象
FileInputStream in = new FileInputStream(getImage());
//3.一边读取一边写入
byte [] data = new byte[1024];//
int len = 0;
while((len=in.read(data))>0){//read()方法,用来将数据读取到数组中,返回读取的个数
out.write(data,0,len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("哈哈,上传cheng共!");
}