struts2上传下载文件及出现的问题 struts2上传下载
在过去的这一周里,断断续续的在做文件上传下载。把这几天遇到的坑,一一写下来,让大家能避免。
1、 开发环境
Struts2.3.20+spring3.2.7+mybatis3.3.0
2、 使用ajaxfileupload.js+JQuery+servlet
在上传的过程中,图片上传不上,下载文件也不完整,有可能报错。
注意在struts2要使用Servlet
Web.xml中
<servlet-mapping>
<servlet-name>XXServlet</servlet-name>
<url-pattern>/XXServlet.servlet</url-pattern>
</servlet-mapping>
页面调用要写成
document.myform.action= "${pageContext.request.contextPath}/XXServlet.servlet";
document.myform.submit();
上传不成功的原因,有可能是struts2拦截不到文件,也有可能是组件不兼容,我在IE7下测试没有问题,但是在IE11下有问题。
百度了N次,好多方法都试过了,结论不行。既然不行,那么老老实实的用struts2自带的上传下载组件吧。
3、 上传主页面
<td bgcolor="#D3DFEF" width="100%" colspan="3">
<iframe id="iframe" scrolling="no" width="100%" height="25" frameborder="0" src="${pageContext.request.contextPath}/Tksm/proplan/UploadFiles.jsp" ></iframe>
</td>
4、 UploadFiles.jsp页面部分代码
function testUpload(){
var excelpath = document.forms[0].upload.value;
var url = '${pageContext.request.contextPath}/modiProImages';
if(excelpath!=null && excelpath!=''){
var ss = excelpath.split('.');
var fileType = ss[ss.length-1];
if(fileType=='jpg'||fileType=='JPG'||fileType=='pdf' || fileType=='PDF'){
document.all.test.action = url;
document.all.test.submit();
}else{
alert("只允许上传.jpg和.pdf类型文件!");
document.all.test.reset();
return ;
}
}else{
alert("请选择上传文件");
return ;
}
}
<form method="post" id="test" action="#" enctype="multipart/form-data">
<table width="100%" cellspacing=0>
<tr>
<td colspan="1" style="solid #8CB1D6;background-color: #D3DFEF;">
<input type="file" name="upload" style="width:360px; height: 24px;">
<button onclick="testUpload();" style="height: 24px;">上传</button>
</td>
</tr>
</table>
</form>
5、 在struts.xml注册
<action name="modiProImages" class="proInfoAction" method="modiProImages">
<result name="success">/Tksm/proplan/UploadFiles.jsp</result>
<result name="error">/WEB-INF/index/error.jsp</result>
<result name="input">/Tksm/proplan/UploadFiles.jsp</result>
</action>
6、 ProInfoAction.java
private File upload;
private String uploadFileName;
private String uploadContentType;
生成setter/getter方法
@SuppressWarnings("unchecked")
public String modiProImages() throws Exception {
request = ServletActionContext.getRequest();
session = request.getSession(true);
Profiles profiles = new Profiles();
File fileinit;
String tmpPath = "D:\\modiimages";
fileinit = new File(tmpPath);
if (!fileinit.isDirectory()){
fileinit.mkdir();
}
String savePath = "modiimages/";
String message = "";
try {
File f = this.getUpload();
//System.out.println("name=="+this.getUploadFileName());
FileInputStream inputstr = new FileInputStream(f);
String wjmc = this.getUploadFileName();
int index = wjmc.lastIndexOf(".");
wjmc = wjmc.substring(index + 1, wjmc.length());
String filename = pronum+"_"+LineNbr+"."+wjmc;
File uploadFile = new File(tmpPath + "/" + filename);
FileOutputStream outputstr = new FileOutputStream(uploadFile);
byte[] buf = new byte[1024];
int length = 0;
while ((length = inputstr.read(buf)) != -1) {
outputstr.write(buf, 0, length);
}
outputstr.flush();
outputstr.close();
inputstr.close();
message = "文件上传成功!";
return "success";
}catch(Exception e){
e.printStackTrace();
message = "文件上传失败";
return "input";
}
}
7、 配置tomcat虚拟目录
在Tomcat x.x\conf\Catalina\localhost文件夹下新建工程同名.xml文件
如果打算是双级虚拟目录,或者多级虚拟目录,写成aa#bb#cc.xml
需要手动在D盘新建modiimages文件夹。
<?xml version='1.0' encoding='utf-8'?>
<Context docBase="D:/modiimages " path="">
</Context>
8、 下载文件
function downFile(filename){
var href="${pageContext.request.contextPath}/downCustFile?fileName="+filename;
document.forms[0].action=href;
document.forms[0].submit();
}
<td align="center" class="tda">
<a href="javascript:downFile('<s:property value="filename"/>')">
<font color="#3300CC"><s:property value="filename"/></font>
</a>
</td>
9、 下载struts2-sunspoter-stream-1.0.jar
10、 Struts.xml中注册方法
<result-types>
<result-type name="streamx" class="com.sunspoter.lib.web.struts2.dispatcher.StreamResultX" />
</result-types>
<action name="downCustFile" class="proInfoAction" method="downCustFile">
<result name="success" type="stream">
点击下载文件时,点击取消会报错:
严重: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
这是一个struts2的bug
<action name="downCustFile" class="proInfoAction" method="downCustFile">
<result name="success" type="streamx">
<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment; filename=${fileName}</param>
<param name="bufferSize">4096</param>
<param name="contentType">application/octet-stream;charset=ISO8859-1</param>
</result>
<result name="error">/WEB-INF/index/error.jsp</result>
</action>
11、 ProInfoAction
private String fileName;
private InputStream inputStream;
生成getter/setter方法
public InputStream getInputStream(){
request = ServletActionContext.getRequest();
String filepath = "/modiimages/"+this.getFileName();
//System.out.println("filepath="+"/"+filepath);
try {
String fullpath = request.getRequestURL().toString();
int index = fullpath.lastIndexOf("/");
fullpath = fullpath.substring(0, index + 1)+filepath;
URL url = new URL(fullpath);
URLConnection conn = url.openConnection();
inputStream = conn.getInputStream();
//System.out.println("inputStream=="+inputStream);
return inputStream;
} catch (MalformedURLException e) {
//e.printStackTrace();
} catch (IOException e) {
//e.printStackTrace();
}
return null;
/*
使用struts2自带的上传
如果使用这段代码,会报如下错误
StreamResultX : 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.
打印
inputStream===null
说明没有找到文件,文件输入流为空
request = ServletActionContext.getRequest();
session = request.getSession(true);
String fname = this.getFileName();
String filepath = "/modiimages/"+fname;
String fullpath = request.getRequestURL().toString();
int index = fullpath.lastIndexOf("/");
fullpath = fullpath.substring(0, index + 1)+filepath;
inputStream = ServletActionContext.getServletContext().getResourceAsStream(fullpath);
System.out.println("inputStream==="+inputStream);
fileName = encodingFileName(fname);
return inputStream;*/
}
public String downCustFile() throws Exception {
return "success";
}
这一篇文章,参考了
https://blog.csdn.net/xiangchengguan/article/details/39860065
http://zfc.iteye.com/blog/1050009
https://www.cnblogs.com/lcngu/p/5094159.html
推荐阅读
-
linux安装mysql5.7.22配置文件my.cnf配置细节及修改密码时出现的问题解决
-
python中通过pip安装库文件时出现“EnvironmentError: [WinError 5] 拒绝访问”的问题及解决方案
-
一个关于struts2上传文件超过限制大小如何提示的问题
-
一个关于struts2上传文件超过限制大小如何提示的问题
-
struts2上传下载文件及出现的问题 struts2上传下载
-
docker使用storage出现Exit导致文件无法上传服务器的问题及解决方案
-
Tomcat 集群 文件上传下载的共享问题 NFS配置
-
php提取csv格式文件中的字符串出现的有关问题及解决方法
-
struts2 文件上传的拦截器问题
-
struts2文件上传下载实例