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

nojave nojave 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
用<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;
}

}
...全文
评论 3
收藏 已收藏
分享
返回顶部
nojave
Web 开发 81,108 成员 341,720 内容