1,文件上传
在jsp中:
<form action="uploadFile.action" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit" value="上传"/>
</from>
在上传的action中
private File file;
private String fileFileName;
private String fileContentType;
public String uploadFile() throws IOException{
String path = ServletActionContext.getServletContext().getRealPath("/upload");
InputStream input = new FileInputStream(file);
OutputStream out = new FileOutputStream(new File(path+fileFileName));
//上传的文件所放位置
byte[] buffer = new byte[1024];
int len =-1;
while((len=input.read(buffer))!= -1){
out.write(buffer, 0, len);
}
out.flush();
out.close();
input.close();
return "success";
}
注意:上面的全局变量前面必须和JSP里面的input标签里面的file的name属性相同。
<input type="file" name="file"/>
private File file;
private String fileFileName;
private String fileContentType;
以上就是上传的action代码了。
2,显示的代码
在action里面:
public String xianshi() throws IOException{
//显示也就是相当于下载显示。
String path = ServletActionContext.getServletContext().getRealPath("/upload");
InputStream input = new FileInputStream(new File(path+fileFileName));
OutputStream out = response.getOutputStream();
byte[] buffer = new byte[1024];
int len =-1;
while((len=input.read(buffer)) != -1){
out.write(buffer,0,len);
}
out.flush();
out.close();
input.close();
return null;
}