[Struts2] 文件上传成功但是出现java.lang.IllegalStateException异常

nojave 2009-11-29 09:14:05
用<s:file> 上传文件,可以正确上传,但是最后出现java.lang.IllegalStateException错误.直接贴代码了
struts.xml

<action name="savecompany" class="companyAction"
method="saveCompany">
<!-- Struts2内置的文件上传拦截器 -->
<interceptor-ref name="fileUpload">
<param name="allowedTypes">
image/bmp,image/gif,image/JPEG,image/pjpeg,image/jpg
</param>
<param name="maximumSize">2048000</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
<result name="success">/operations.jsp</result>
</action>


action:


public String saveCompany() {
System.out.println("upload file");
// upload file
HttpServletRequest request = ServletActionContext.getRequest();
// Get real path
String realpath = request.getSession().getServletContext().getRealPath(
"/");
//save path is a directory
String savepath = realpath + "images\\" + this.getId();
String filetype = this.getLogoContentType();
//create file type
filetype = filetype.replace("image/", "");
filetype = filetype.replace("pjpeg", "jpg");

try {
if (CreatePath(savepath) == false) {
throw new SystemException("创建文件夹失败,");
} else {
//file = save path + logo. + file type
String savefile = savepath + "\\" + "logo." + filetype;
File tarFile = new File(savefile);
System.out.println(savefile);
fu.uploadFile(this.getLogo(), tarFile);
}
} catch (Exception e) {
throw new SystemException("文件上传失败,");
}
return SUCCESS;
}


上传文件的Function:

package com.prodinfo.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import com.opensymphony.xwork2.ActionSupport;

public class FileUpload extends ActionSupport implements IFileUpload {

private static final int BUFFER_SIZE = 2048000;

public String uploadFile(File src, File target) {
try {
FileOutputStream fileout = new FileOutputStream(target);
FileInputStream filein = new FileInputStream(src);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = filein.read(buffer)) > 0) {
fileout.write(buffer, 0, len);
}
fileout.close();
filein.close();
} catch (Exception e) {
throw new SystemException("文件上传失败,");
}
return SUCCESS;
}

}
...全文
219 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
nojave 2009-11-30
  • 打赏
  • 举报
回复
问题解决了,是web.xml里多配了一个FORWARD.
nojave 2009-11-30
  • 打赏
  • 举报
回复
发现是在action : saveCompany() 执行完毕之后return SUCCESS给struts.xml执行页面跳转时才发生的错误,很纳闷.
海川520 2009-11-30
  • 打赏
  • 举报
回复
FileUtils.copyFile(fileResources, destFile);
struts 2文件上传在action我就用这一句就可以了,你配置哪些有什么用
fileResources:为表单的名字;action中定义File类型。File fileResources = null;

destFile:为你要保存的路径:可以自己定义路径 File destFile = new File("c:/");

81,094

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧