0%

Struts2 下载文件异常解决

异常描述

异常截图

Java代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package action.upload;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Map;

/**
* @author : Waver
* @date : 2018/3/19 20:35
*/
public class DownloadAction extends ActionSupport {

/**
* 获取文件路径
*/
private String savePath;
/**
* 接收的文件名
*/
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getSavePath() {
return savePath;
}

public void setSavePath(String savePath) {
this.savePath = savePath;
}

public String list() {
File file = new File(savePath);
String[] list = file.list();
ActionContext context = ActionContext.getContext();
Map<String, Object> contextMap = context.getContextMap();
contextMap.put("list", list);
return "list";
}

public InputStream getInputStream() {
try {
FileInputStream fileInputStream = new FileInputStream(new File(savePath + name));
return fileInputStream;
} catch (FileNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("下载异常!!!");
}
}

public String down(){
return "down";
}


}

xml配置信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<struts>
<package name="upload" extends="struts-default" namespace="/upload">
<action name="upload" class="action.upload.UploadAction" method="execute">
<interceptor-ref name="defaultStack">
<param name="fileUpload.allowedTypes">image/jpeg,image/jpg</param>
</interceptor-ref>
<param name="savePath">e:/upload/</param>
<result>/login.jsp</result>
<result name="input">/error.jsp</result>
</action>

<action name="down_*" class="action.upload.DownloadAction" method="{1}">
<param name="savePath">e:/upload</param>
<result name="list">/listFile.jsp</result>
<result type="stream" name="down">
<!--返回给浏览器的文件类型, 返回通常用二进制-->
<param name="contentType">applicantion/octet-stream</param>
<!--返回给浏览器的输入流-->
<param name="inputName">inputStream</param>
<!--告诉浏览器以下载的方式下载资源-->
<param name="contentDisposition">attachment=${name}</param>
<!--缓存大小-->
<param name="bufferSize">1024</param>
</result>
</action>
</package>
</struts>

错误原因及解决方案

<param name="savePath">e:/upload</param> 项后没有加 “/“ 与文件名组合后无法找到文件名应改为 <param name="savePath">e:/upload/</param>