structs文件上传,
空指针问题
jsp代码
<body>
<form action="/test/upload.do?action=uploadFile" method="POST" enctype="multipart/form-data" name="form1">
图片 <input type="file" name="uploadcover">
描述 <input type="text" name="title" size="20">
<input type="submit" value="上传">
</form>
</body>
action代码:
public ActionForward uploadFile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse reponse)throws Exception{
initAction(request, mapping);
UploadForm uploadForm=(UploadForm)form;
if(uploadForm!=null){
String title=uploadForm.getTitle();
System.out.println(title);
FormFile file=uploadForm.getUploadcover();
if(file!=null){
String fileName=file.getFileName();
if(!(file==null||"".equals(file.getFileName()))){
String path="d:\\test\\"+fileName+".jpg";
path=path.replaceAll("\\\\","/");
String pathName=null;
if(path.endsWith("/") ){
pathName=path;
pathName+=fileName;
}else{
pathName=path.substring(0,path.indexOf("/"));
}
File dir=new File(pathName);
if(!dir.isDirectory()){
dir.mkdirs();
try{
InputStream stream=file.getInputStream();
byte buffer[]=new byte[8192];
int bytesRead=0;
FileOutputStream fos=new FileOutputStream(path);
while((bytesRead=stream.read(buffer,0,8192))!=-1){
fos.write(buffer,0,bytesRead);
}
fos.flush();
fos.close();
}catch(
IOException e){
e.printStackTrace();
return findForward("error");
}
return findForward("success");
}
}
}
}
return findForward("error");
}
actionfor代码:
public class UploadForm extends ActionForm {
private FormFile uploadcover;
private String title;
public FormFile getUploadcover() {
return uploadcover;
}
public void setUploadcover(FormFile Uploadcover) {
this.uploadcover = Uploadcover;
}
public String getTitle(){
return this.title;
}
public void setTitle(String title){
this.title=title;
}
}
FormFile file=uploadForm.getUploadcover();此处file为空?为什么?title中有内容,uploadcover为空?
------解决方案--------------------
你这是struts 1.x。
1、UploadForm 是如何写的,如何定义uploadcover这个属性的。(