每回碰到上传下载的功能时都需要花费相对多的功夫来重新组织,今天索性就总结一个自己常用的方法。
1.JSP页面怎么写
<input type="hidden" value="XXXX" name="fileName" style="display: none;">
<input type="submit" value="下载文件">
2.Action怎么写
private String fileName;
private String dataName;
public String getFileName() {
//设置客户端默认字符集编码
ServletActionContext.getResponse().setHeader("charset","ISO8859-1");
try {
return new String(this.fileName.getBytes(), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "";
}
}
public void setFileName(String fileName) {//这个名字是你点击保存时的文件名,一般如果信息比较机密可以采用替换文件名的方式
dataName = fileName;
this.fileName = "test.sql";
}
public InputStream getInputStream(){
String dbName = "java"+dataName;
ExportMysql ex = new ExportMysql();
ex.exportMysql("e://", dbName);
try {
return new FileInputStream("e://java"+dataName+".sql");
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
public String execute() throws IOException {
return SUCCESS;
}
3.struts.xml文件的配置
<action name="fileDownload" class="com.test.action.filedown.FileDownloadAction"> <result name="success" type="stream"> <!-- 动态文件下载的,事先并不知道未来的文件类型,那么我们可以把它的值设置成为:application/octet-stream;charset=ISO8859-1 ,注意一定要加入charset,否则某些时候会导致下载的文件出错; --> <param name="contentType"> application/octet-stream;charset=ISO8859-1 </param> <param name="contentDisposition">attachment;filename="${filename}"</param> <!-- 使用经过转码的文件名作为下载文件名,downloadFileName属性 对应action类中的方法 getDownloadFileName() 其中特殊的代码就是${downloadFileName},它的效果相当于运行的时候将action对象的属性的取值动态的填充在${}中间的部分,我们可以认为它等价于+action. getDownloadFileName()。 --> <param name="inputName">inputStream</param> <param name="bufferSize">4096</param> </result> </action>基本的框架就是如此,暂时还不是太明白其中的原理,等慢慢熟悉后再修改这篇文章,请轻拍。