日期:2014-05-20  浏览次数:20784 次

求解:Struct2 上传图片报java.lang.NullPointerException错误
上传UpLoad.jsp:
<s:actionerror/>
   
  <s:form action="upload" enctype="multipart/form-data" method="post">
  <s:label value="上传文件"/>
  <s:file name="picture" label="文件一"/>
 
  <s:submit value=" 开始上传 " method="upload"></s:submit>
  </s:form>
上传成功页面 UploadList.jsp:
<body>
  文件已经保存到:
<a href="upload/<s:property value="pictureFileName" />"
target=_blank><s:property value="pictureFileName" />
</a>
<br/>
<br/>
&lt;&lt;<a href="upload.action">继续上传</a>
  </body>
UploadAction:
public class UploadAction extends ActionSupport{
private static final long serialVersionUID = -60950803930068947L;

private File picture;

private String pictureContentType;

private String pictureFileName;

public String execute() {

  

return "input1";
}

public String upload() throws Exception {
   


System.out.println("Context: "+ ServletActionContext.getServletContext().getRealPath("upload"));

System.out.println("File: " + picture);

System.out.println("FileName: " +pictureFileName );

File saved = new File(ServletActionContext.getServletContext()
.getRealPath("upload"), pictureFileName);

System.out.println("saved : " +saved);

InputStream ins = null;
OutputStream ous = null;

try {
saved.getParentFile().mkdirs();

ins = new FileInputStream(picture);
ous = new FileOutputStream(saved);

byte[] b = new byte[1024];
int len = 0;

while ((len = ins.read(b)) != -1) {
ous.write(b, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ous != null)
ous.close();
if (ins != null)
ins.close();
}

return "list";
}

public File getPicture() {
return picture;
}

public void setPicture(File file) {
this.picture = file;
}

public String getPictureContentType() {
return pictureContentType;
}

public void setPictureContentType(String fileContentType) {
this.pictureContentType = fileContentType;
}

public String getPictureFileName() {
return pictureFileName;
}

public void setPictureFileName(String fileFileName) {
this.pictureFileName = fileFileName;
}
}
struct.xml:
<action name="upload" class="cn.gov.pbc.action.UploadAction" method="upload">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">image/bmp,image/x-png,image/gif,image/jpeg</param>
<param name="maximumSize">204800</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
<result name="input1">/UpLoad.jsp</result>
<result name="list">/UploadList.jsp</result>
</action>
 

------解决方案--------------------
你把
System.out.println("Context: "+ ServletActionContext.getServletContext().getRealPath("upload"));
System.out.println("File: " + picture);
System.out.println("FileName: " +pictureFileName );
下面的代码屏蔽掉,看看能不能获取到文件名。。