今天在用struts2就行文件下载时出现以下错误:java
说实话这个提示真有误导人的嫌疑,刚开始还觉得是名称不对,估计通常人看到这个提示都这样想。而后查看StreamResult的源代码才发现是由于InputStream为null的缘故,汗一个。看下源码:apache
你们若是也碰到此类问题,直接打印
InputStream in=ServletActionContext.getServletContext().getResourceAsStream(realPath);
System.out.println(in);
若是打印为NULL的话,恭喜您,问题得以解决,问题的缘由是这个流的realPath路径错误,app
还没明白的往下看ide
怪呀,个人配置应该没错呀
页面上:
<a href="fileDownload.action?fileName=<s:property value ="imageName" />">下载此图片</a>
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="${downloadFileName}"
</param>
<!-- 使用通过转码的文件名做为下载文件名,downloadFileName属性
对应action类中的方法 getDownloadFileName() 其中特殊的代码就是${downloadFileName},它的效果至关于运行的时候将action对象的属性的取值动态的填充在${}中间的部分,咱们能够认为它等价于+action. getDownloadFileName()。 -->
<param name="inputName">inputStream</param>
<param name="bufferSize">4096</param>
</result>
</action>
----------------------------------------------------------
action中
----------------------------------------------------------
private String fileName;// 初始的经过param指定的文件名属性 set get
/** 文件名 转换编码 防止中文乱码*/
public String getDownloadFileName() {
String fileName=ServletActionContext.getRequest().getParameter("fileName");
String downFileName = fileName;
try {
downFileName = new String(downFileName.getBytes(), "ISO8859-1");
} catch (Exception e) {
e.printStackTrace();
}
return downFileName;
}
//下载的流
public InputStream getInputStream() {
String name=this.getDownloadFileName();
// String realPath=ServletActionContext.getServletContext().getRealPath("/uploadImages")+ "/"+name; 路径错误
String realPath="/uploadImages/"+name;
InputStream in=ServletActionContext.getServletContext().getResourceAsStream(realPath);
if(null==in){
System.out.println("Can not find a java.io.InputStream with the name [inputStream] in the invocation stack. Check the <param name=\"inputName\"> tag specified for this action.检查action中文件下载路径是否正确.");
}
return ServletActionContext.getServletContext().getResourceAsStream(realPath);
}
@Override
public String execute() throws Exception {
return SUCCESS;
}
this