配置文件省略
1.上传页面
<form action="upload.html" enctype="multipart/form-data" method="post">
上传文件:<input type="file" name="upload" /><br />
上传日期:<input type="text" name="upDate" /><br />
<input type="submit" value="提交" />
</form>
2.Action
@Controller
@ParentPackage("json-default")
public class UploadAction extends ActionSupport {
private File upload;//要上传的文件对象(upload必须是页面File控件的name属性一致)
private String uploadContentType;//要上传文件的类型(页面File控件的name属性+ContentType)
private String uploadFileName;//要上传的文件名称(页面File控件的name属性+FileName)
private String savePath;//获取上传文件的保存路径
private String InputStream inputStream;//下载文件的输入流
private Date upDate;//上传日期
/**省略getter和setter**/
/**上传单个文件**/
@Action(value="upload",results={@Result(name="success",location="/upload.jsp")})
public String upload(){
byte[] buffer=new byte[1024];//缓冲数据,每秒以1kb的速度上传文件(可调)
try{
//读取要上传的文件
FileInputStream fis=new FileInputStream (upload);
//获得保存的路径,将文件保存在根目录的upload的文件夹内
savePath=ServletActionContext.getServletContext().getRealPath(/upload);
//检查上传的文件夹是否存在,不存在则新建
File file=new File(savePath);
if(!file.exists()){
file.mkdirs();
}
//对要上传的文件进行重命名,避免上传同一个文件导致覆盖
//获取原文件的后缀名
String exName=FilenameUtils.getExtension(uploadFileName);
//生成新的文件名:当前系统时间+上传文件的哈希值+后缀名
String newName=System.currentTimeMillis+upload.hashCode()+"."+exName;
//将读到的文件保存到制定位置
FileOutputStream fos=new FileOutputStream(savePath+"\\"+newName);
//用session保存新的文件名
ServletActionContext.getRequest().getSession().setAttribute("newName", newName);
//使用缓冲读入信息并完成文件的保存工作
int length=fis.read(buffer);
while(length>0){//只要还能读到东西就一直保存
fos.write(buffer,0,length);//从最开始的位置开始读,直到最后的位置
length=fis.read(buffer);
}
//关闭配置
fis.close();
fos.flush();
fos.close();
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return SUCCESS;
}
/**下载文件**/
@Action(value="download",results= {@Result(name="success",type="stream",params={"contentType","application/octet-stream",
"inputName","inputStream",
"contentDisposition","attachment;filename=${uploadFileName}",
"bufferSize","4096"})})//type="stream" "attachment;filename=${uploadFileName}" 中的${uploadFileName}是下载的文件的文件名,"bufferSize","4096"是下载的缓冲
public String download(){
return SUCCESS;
}
}