html:
///
下载
$().ready(function(){
$("#download")
.button()
.click(
function(){
deleteUserForm.action = "downloadFile.action";
deleteUserForm.submit();
}
);
});struts.xml
attachment;filename="${fileName}"
downloadFileStream
UserAction
private String fileName;
public String getFileName() {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-DD");
String fileName = sf.format(new Date()).toString() + ".xls";
try {
fileName = new String(fileName.getBytes(),"utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String downloadFile(){
return SUCCESS;
}
public InputStream getDownloadFileStream(){
String directory = "/upload";
String targetDirectory = ServletActionContext.getServletContext().getRealPath(directory);
try {
return new FileInputStream(new File(targetDirectory, uploadFileFileName));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
struts.xml 中fileName 对应 action中fileName, downloadStream对应action中 getDownloadStream, get方法首字母小写。
根据路径+文件名,返回文件流。
fileName可直接根据时间设置,也可以根据目录列出文件名获取。
fileList = getfiles(getdbName);
public String getfiles(String dbDir){
// String t=Thread.currentThread().getContextClassLoader().getResource("").getPath();
// System.out.println(t);
// if(t.indexOf("WEB-INF")>0)
// t = t.substring(1,t.indexOf("/WEB-INF/classes"));
String t ="C:/DB_Backup";
if(dbDir != null && !dbDir.equals("")){
t +="/"+dbDir;
}
String str = readFile(t);
return str;
}
public String readFile(String fileName) {
String output = "";
File file = new File(fileName);
if(file.exists()){
if(file.isFile()){
try{
BufferedReader input = new BufferedReader (new FileReader(file));
StringBuffer buffer = new StringBuffer();
String text;
while((text = input.readLine()) != null)
buffer.append(text +"\n");
output = buffer.toString();
} catch(IOException ioException){
System.err.println("File Error!");
}
} else if(file.isDirectory()){
String[] dir = file.list();
// output += "Directory contents:\n";
for(int i=0; i
output += dir[i] +",";
}
}
} else{
System.err.println("Does not exist!");
}
return output;
}