日期:2014-05-19  浏览次数:20699 次

struts1文件上传报错
html部分:
<form action="/control/bank/manage.do?method=addBankProduct" 
method="post" enctype="multipart/form-data">
<input type="file" name="imageFile" />

formbean部分:

@Uploaded(location = "/images/bank", extensions = {"gif", "jpg", "png", "bmp"})
private File imageFile;

同时给File加上set、get方法。


运行报错:文件类型不匹配、当把set方法去了的时候报空指针
at cn.togo.web.action.privilege.PrivilegeProcessor.saveFile(PrivilegeProcessor.java:64)


纠结
struts 文件上传 类型不匹配?空指针 空指针 类型不匹配

------解决方案--------------------
struts1没有直接调用页面属性的方法,必须request.getParameter("imageFile");
------解决方案--------------------
定义一个 UploadForm extends ActionForm  类 用于接收文件

定义变量:
private org.apache.struts.upload.FormFile file;

Action配置这个form 可以直接获取

页面:

<form action="/control/bank/manage.do?method=addBankProduct"  name="uploadForm"  
method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" style="width:200px;" />
              
------解决方案--------------------
引用:
来人啊

在actionform中private FormFile file;封装方法
FormFile formfile = caifuform.getFile();
try {
InputStream stream = formfile.getInputStream();
String filePath = request.getRealPath("/");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream bos = new FileOutputStream(filePath + "/" +formfile.getFileName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ( (bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
stream.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
赋值时:对象.set属性(formfile.getFileName());
页面<html:file property="file"></html:file>