在过去的这一周里,断断续续的在做文件上传下载。把这几天遇到的坑,一一写下来,让大家能避免。
1、 开发环境
Struts2.3.20+spring3.2.7+mybatis3.3.0
2、 使用ajaxfileupload.js+JQuery+servlet
在上传的过程中,图片上传不上,下载文件也不完整,有可能报错。
注意在struts2要使用Servlet
Web.xml中
<servlet-mapping>
<servlet-name>XXServletservlet-name>
<url-pattern>/XXServlet.servleturl-pattern>
servlet-mapping>
页面调用要写成
document.myform.action= "${pageContext.request.contextPath}/XXServlet.servlet";
document.myform.submit();
上传不成功的原因,有可能是struts2拦截不到文件,也有可能是组件不兼容,我在IE7下测试没有问题,但是在IE11下有问题。
百度了N次,好多方法都试过了,结论不行。既然不行,那么老老实实的用struts2自带的上传下载组件吧。
3、 上传主页面
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 ;
}
}
上传
5、 在struts.xml注册
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文件夹。
8、 下载文件
function downFile(filename){
var href="${pageContext.request.contextPath}/downCustFile?fileName="+filename;
document.forms[0].action=href;
document.forms[0].submit();
}
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>
点击下载文件时,点击取消会报错:
严重: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
这是一个struts2的bug
inputStream
attachment; filename=${fileName}
4096
application/octet-stream;charset=ISO8859-1
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 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