上传文件要添加两个jar包commonse,在pom中添加
<!--文件上传,添加这个就直接帮助我们自动添加其他所需的依赖-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<!--javax 获取文件路径的时候使用-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
页面中的配置,要使用post方式提交,添加属性enctype="multipart/form-data"
<form method="post" action="/fileUpload.action" enctype="multipart/form-data" >
<input name="user" />
<input name="pass"/>
<input type="file" name="file"/>
<button type="submit">提交</button>
</form>
在action中的配置,添加三个属性,这三个属性必须要创建,否则会报错.当然不要忘记set/get方法
public File file;//io包中的file
public String fileFileName;//接收到的文件的名字
public String fileContentType;//接收到的文件的类型
上传文件的方法如下
@Action(value = "/fileUpload" ,results = {@Result(name = "success" ,location = "/seccess.jsp",type = "redirect")})
public String fileUpload() throws IOException {
//获得输入流,读取文件的内容
FileInputStream fileInputStream=new FileInputStream(file);
byte[] b=new byte[102400];
fileInputStream.read(b);
//获取项目系统路径
HttpServletRequest request = ServletActionContext.getRequest();
//获取文件的路径
String path=request.getServletContext().getRealPath(fileFileName);
//获取最后一个斜杠的位置
int weizhi = path.lastIndexOf("\\");
//将文件的路径进行改写
String newPath = path.substring(0, weizhi);
File newFile=new File(newPath+"\\file\\"+fileFileName);
//将文件写入上面定义的文件夹中
FileOutputStream fileOutputStream=new FileOutputStream(newFile);
fileOutputStream.write(b);
fileInputStream.close();
fileOutputStream.close();
return "success";
}