这里我上传文件,我想读取文件类型和文件扩展名,但是当我给文件在FileUtils.copyFile(this.uploadFile,fileToCreate)附近获得nullpointer异常时;任何人都可以解决这个问题...
public class ImportAction extends ActionSupport implements ServletRequestAware {
private static final long serialVersionUID = 1L;
private File uploadFile;
private String uploadFileName;
private String uploadContentType;
private HttpServletRequest servletRequest;
public File getUploadFile() {
return uploadFile;
}
public void setUploadFile(File uploadFile) {
this.uploadFile = uploadFile;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
RegisterDAO dao = new RegisterDAO();
/**
*
* @return
* @throws
* Exception
*/
@SuppressWarnings("unchecked")
@Override
public String execute() throws Exception {
try {
String filePath = servletRequest.getSession().getServletContext().getRealPath("/");
System.out.println("Server path:" + filePath);
File fileToCreate = new File(filePath, this.uploadFileName);
FileUtils.copyFile(this.uploadFile, fileToCreate);
} catch (Exception e) {
e.printStackTrace();
addActionError(e.getMessage());
return INPUT;
}
Model m = new Model();
String result = m.fileimport(uploadFile, uploadFileName);
if (result.equals(SUCCESS)) {
return SUCCESS;
} else {
addActionError(getText(result));
return "failure";
}
}
@Override
public void validate() {
System.out.println("inside validate of LA");
}
@Override
public void setServletRequest(HttpServletRequest hsr) {
this.servletRequest = hsr; //To change body of generated methods, choose Tools | Templates.
}
}
这是我的jsp页面
<s:form method="post" action="file" enctype="multipart/form-data">
<s:file label="choose file" name="uploadFile"></s:file>
<s:submit></s:submit>
</s:form>
我打印我的文件路径就像这样 filepathD:\兰芝斯\ ranjithdemo3 \构建\网络\
答案 0 :(得分:1)
这是在不到24小时内使用此代码的第三个问题......这是由在线arcticle拍摄的吗?你能在这报告吗?
BTW,主要问题是在使用Struts2上传文件时,通过fileUploadInterceptor,你必须尊重以下结构private File <filevarname>;
private String <filevarname>FileName;
private String <filevarname>ContentType;
所以如果您的<filevarname>
是“uploadFile”,那么您应该
private File uploadFile;
private String uploadFileFileName;
private String uploadFileContentType;
如果您将其更改为“上传”,则应为
private File upload;
private String uploadFileName;
private String uploadContentType;
对我来说更具可读性。
答案 1 :(得分:0)
请检查;
答案 2 :(得分:0)
检查您的操作类中的内容类型字段是否从uploadContentType
重命名为uploadFileContentType
。
同时将uploadFileName
更改为uploadFileFileName
。
也改变相应的getter和setter。我不确定它是否导致了这个问题。所以这是一种更多的试错建议。
更新: 看来你正在接受GET行动的NPE。
在尝试阻止之前添加以下代码:
if(!servletRequest.getMethod().equalsIgnoreCase("POST")){
return INPUT;
}
这不是很优雅,但应该适用于此示例。我检查了一下。 :)