关于文件下载
1,文件下载可以直接通过简单的链接实现,但不能设置权限,也不能下载被保护的文件。
2,接下来我将使用struts2的文件下载,首先,要写一个下载页面,downloadFile.jsp,直接在地址栏传三个参数:
<a href="D:\hardwork\照片\1.jpg">下载照片</a>
<a href="D:\hardwork\照片\11.txt">下载文本</a>
<a href="WEB-INF\2.jpg">在被保护的文件中</a>
<a href="download?inputPath=D:\hardwork\照片\2.jpg&contentType=image/jpeg&downFileName=我的照片">下载</a>
接下来,再写FileDownloadAction.java文件,这个action方法需要提供一个返回InputStream的方法,该输入流代表了被下载文件的入口,且需要配置stream类型结果时指定inputName参数,inputName参数值就是方法去掉get前缀,首字母小写的字符串。
public class FileDownloadAction extends ActionSupport {
//下载文件的资源路径
private String inputPath;
private String contentType;
//下载文件的下载文件名
private String downFileName;//和struts.xml文件中的参数相对应
public String getInputPath() {
return inputPath;
}
public void setInputPath(String inputPath) {
this.inputPath = inputPath;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getDownFileName() {
return downFileName;
}
public void setDownFileName(String downFileName) {
this.downFileName = downFileName
}
public InputStream getTargetFile() throws Exception{
//return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
FileInputStream fis=new FileInputStream(inputPath);
return fis;
}
}
最后就是要配置struts.xml文件了,在配置文件中使用OGNL表达式可以加引号,也可以不加。
<action name="download" class="nuc.sw.action.FileDownloadAction">
<result name="success" type="stream">
<!-- 指定下载文件的文件类型 -->
<param name="contentType">${contentType}</param>
<param name="inputName">targetFile</param>
<!-- 指定下载文件的文件名 -->
<param name="contentDisposition">filename="${downFileName}"</param>
<!-- 指定下载文件的缓冲大小 -->
<param name="bufferSize">4096</param>
</result>
</action>
如果按照上述操作,则会遇到如下问题:
(1)如果地址栏传参传的是英文状态下的,且是照片,则会直接将照片显示出来,不会出现下载的页面,要解决这个问题,则需要将struts.xml文件中的配置进行更改如下
<param name="contentDisposition">attachment;filename="${downFileName}"</param>
这里的attachment是指以附件的形式下载,这样就可以出现下载页了。
(2)如果文件名是中文,则保存的是乱码形式,这就需要将文件名和所在的资源路径进行转码,更改action文件如下所示:
public void setInputPath(String inputPath) throws UnsupportedEncodingException {
this.inputPath=new String(inputPath.getBytes("iso-8859-1"),"utf-8");
}
public void setDownFileName(String downFileName) throws UnsupportedEncodingException {
this.downFileName = new String(downFileName.getBytes("iso-8859-1"),"utf-8");;
}
这样就将下载页中的乱码进行解决
(3)但随之而来的不是乱码,
这就要考虑是什么问题造成的,回溯到downFileName,在struts.xml文件中要获取filename=${downFileName},这里的downFileName是从action中的getDownFileName() 所获取到的,所以需要对这个这个方法获取的值进行转码,如下所示:
public String getDownFileName() throws UnsupportedEncodingException {
return URLEncoder.encode(downFileName,"utf-8");
}
对于 URLEncoder这里有相关的介绍
https://my.oschina.net/zimingforever/blog/63719
这样文件下载就做好了!