今天在用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