SSH2中配合注解的方式如何上传文件?package chinaas.member.action.userPhoto;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;import javax.annotation.Resource;import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.stereotype.Controller;import chinaas.member.action.BaseAction;
import chinaas.member.entity.Photo;
import chinaas.member.service.userPhoto.UserPhotoService;@Controller
@Namespace("/")
@ParentPackage(value = "struts-default")
@Results(@Result(name = "fail", location = "/failed.jsp"))
//@InterceptorRefs( { @InterceptorRef(value = "fileUploadStack"),@InterceptorRef(value="defaultStack")})
public class UserPhotoAction extends BaseAction {
// 用户管理Service
@Resource(name = "userPhotoServiceImpl")
private UserPhotoService userPhotoService; // 上传文件
@SuppressWarnings("static-access")

@Action(value = "/upload", results = { @Result(name = SUCCESS, location = "/success.jsp") },interceptorRefs={@InterceptorRef(value="fileUploadStack")})
public String uploadPhoto() throws Exception {
System.out.println("upload");
//User u = (User) this.s2Util.getSession().getAttribute("user");
System.out.println(">>>>>>>>>>>>>>>>>>"+ServletActionContext.getRequest().getRealPath("/upload"));
System.out.println("tmpFile>>>>>>>"+file);
for(int i=0;i<file.size();i++){
InputStream is=new FileInputStream(file.get(i));
//String root=this._resourcePath+"user/";
String root=this._resourcePath+"user/";
File destFile=new File(root,this.getFileFileName().get(i));
OutputStream os=new FileOutputStream(destFile);
byte[] buffer=new byte[1024*1024*5];
int length=0;
while((length=is.read(buffer))>0){
os.write(buffer, 0, length);
}
/*Photo p = new Photo();
p.setAddTime(UtilTools.getDate());
p.setUploaderId(1);
p.setPhotoName((this.getTmpFileFileName().get(i)));
p.setDescribes(po.getDescribes());
userPhotoService.addPhoto(p);*/
is.close();
os.close();
} msg="用户上传图片成功!";
return SUCCESS;
}


private String msg;
private Photo po;
private List<File> file;//用户上传的文件
private List<String> fileFileName;//后缀是固定的,struts2自动将值填充
private List<String> fileContentType;
public Photo getPo() {
return po;
}
public List<File> getFile() {
return file;
}
public void setFile(List<File> file) {
this.file = file;
}
public List<String> getFileFileName() {
return fileFileName;
}
public void setFileFileName(List<String> fileFileName) {
this.fileFileName = fileFileName;
}
public List<String> getFileContentType() {
return fileContentType;
}
public void setFileContentType(List<String> fileContentType) {
this.fileContentType = fileContentType;
}
public void setPo(Photo po) {
this.po = po;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}

}
结果包空指针~~~~
java.lang.NullPointerException
chinaas.member.action.userPhoto.UserPhotoAction.uploadPhoto(UserPhotoAction.java:46)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:597)
com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:440)
com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:279)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:242)
com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:93)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:306)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:236)
org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:468)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:76)

解决方案 »

  1.   

    java.lang.NullPointerException
    chinaas.member.action.userPhoto.UserPhotoAction.uploadPhoto(UserPhotoAction.java:46) UserPhotoAction.java 46行NullPointerException
    调试一下,看看哪个对象是NULL
      

  2.   

    就是表单域的file没接收到~请问下注解的情况下进行文件上传我那样写对吗?刚接触注解~
      

  3.   

    噢~不过谢谢你啦~哥们~有空一起dota
      

  4.   

    不要注解能否取到文件?先保证不要注解能取到,再变注解。struts文件上传本来就有点麻烦的,何况你这里看起来似乎是个文件列表。
      

  5.   

    chinaas.member.action.userPhoto.UserPhotoAction.uploadPhoto(UserPhotoAction.java:46) 
    这一行的代码是什么?
      

  6.   

    我感觉应该是文件上传到服务器里路径的问题。
    以前也遇到过这种问题。

    String root=this._resourcePath+"user/"; 
    File destFile=new File(root,this.getFileFileName().get(i)); 
      

  7.   

    chinaas.member.action.userPhoto.UserPhotoAction.uploadPhoto(UserPhotoAction.java:46) UserPhotoAction 这个类看看.
      

  8.   

    //SavePath
    private String SavePath ;
    ServletActionContext.getRequest().getRealPath(SavePath) ;再Struts的配置文件中
    上传文件拦截器
    <param name="SavePath">/upload</param><<项目实践精解>>梁立新的书上就有参考一下。
      

  9.   

    System.out.println(">>>>>>>>>>>>>>>>>>"+ServletActionContext.getRequest().getRealPath("/upload")); 就这个路径错了 ,建议先改个物理路径试试 . 还有你用的什么上传组件 建议使用 upload 的jar包 这样容易些 开发效率也会大大提高
      

  10.   

    chinaas.member.action.userPhoto.UserPhotoAction.uploadPhoto(UserPhotoAction.java:46)  这是哪一行啊?
      

  11.   

    @Controller
    @Namespace("/")
    @ParentPackage(value = "struts-default")
    @Results(@Result(name = "fail", location = "/failed.jsp"))
    //@InterceptorRefs( { @InterceptorRef(value = "fileUploadStack"),@InterceptorRef(value="defaultStack")})
    public class UserPhotoAction extends BaseAction { private static final long serialVersionUID = 6660814006888145788L;
    // 用户相册管理Service
    @Resource(name = "userPhotoServiceImpl")
    private UserPhotoService userPhotoService; //指定上传时的缓存大小为1MB
    private static final int BUFFER_SIZE = 1 * 1024 * 1024;
    //上传的文件和表单域的name一致
    private File myFile;
    //上传文件的MIME类型
    private String contentType;
    //上传文件的文件名,该文件名不包括文件的路径
    private String fileName;
    private String msg;
    private Photo po;

    public Photo getPo() {
    return po;
    } public void setPo(Photo po) {
    this.po = po;
    } public String getMsg() {
    return msg;
    } public void setMsg(String msg) {
    this.msg = msg;
    } public void setMyFileContentType(String contentType) {
    this.contentType = contentType;
    } public void setMyFileFileName(String fileName) {
    System.out.println("fileName>>>>>>>>>>>>>>>>" + fileName);
    this.fileName = fileName;
    } public void setMyFile(File myFile) {
    this.myFile = myFile;
    }
    /**
     * 上传文件时IO流操作(上传时所需函数1)
     * @param src 表单域接收的源文件
     * @param dst 上传的文件保存地址
     * 
     * */
    private static boolean copy(File src, File dst) {
    try {
    InputStream in = null;
    OutputStream out = null;
    try {
    in = new BufferedInputStream(new FileInputStream(src),
    BUFFER_SIZE);
    out = new BufferedOutputStream(new FileOutputStream(dst),
    BUFFER_SIZE);
    byte[] buffer = new byte[BUFFER_SIZE];
    while (in.read(buffer) > 0) {
    out.write(buffer);
    }
    } finally {
    if (null != in) {
    in.close();
    }
    if (null != out) {
    out.close();
    }
    }
    } catch (Exception e) {
    e.printStackTrace();
    System.out.println("文件保存时发生错误>>>>>>>"+e.getMessage());
    return false;
    }
    return true;
    }
    /**
     * 获取上传文件的扩展名(上传时所需函数2)
     * @param fileName 上传文件的文件名,该文件名不包括文件的路径
     * @return 扩展名(String)
     * */
    private static String getExtention(String fileName) {
    System.out.println("fileName>>>>>>>>>>>>>>>>" + fileName);
    int pos = fileName.lastIndexOf(".");
    return fileName.substring(pos);
    }

    @SuppressWarnings("static-access")
    @Action(value = "/upload", results = { @Result(name = SUCCESS, location = "/success.jsp") }, interceptorRefs = { @InterceptorRef("fileUploadStack") })
    public String upload()throws Exception{
    //由系统时间生成的文件名,数据库保存的文件名
    String imageFileName = new Date().getTime() + getExtention(fileName);
    //File imageFile = new File(ServletActionContext.getServletContext().getRealPath("/UploadImages") + "/" + imageFileName);
    File imageFile = new File(this._resourcePath + "/user/" + imageFileName);
    if(copy(myFile, imageFile)){
    Photo p=new Photo();
    p.setPhotoName(imageFileName);
    p.setAddTime(UtilTools.getDate());
    p.setDescribes(po.getDescribes());
    p.setUploaderId(1);
    userPhotoService.addPhoto(p);
    msg="上传成功!";
    return SUCCESS;
    }else{
    msg="上传失败!";
    return "fail";
    }
    }}
    这个是最终的正确结果~
      

  12.   


    @Controller
    @Namespace("/")
    @ParentPackage(value = "struts-default")
    @Results(@Result(name = "fail", location = "/failed.jsp"))
    //@InterceptorRefs( { @InterceptorRef(value = "fileUploadStack"),@InterceptorRef(value="defaultStack")})
    public class UserPhotoAction extends BaseAction { private static final long serialVersionUID = 6660814006888145788L;
    // 用户相册管理Service
    @Resource(name = "userPhotoServiceImpl")
    private UserPhotoService userPhotoService; //指定上传时的缓存大小为1MB
    private static final int BUFFER_SIZE = 1 * 1024 * 1024;
    //上传的文件和表单域的name一致
    private File myFile;
    //上传文件的MIME类型
    private String contentType;
    //上传文件的文件名,该文件名不包括文件的路径
    private String fileName;
    private String msg;
    private Photo po;

    public Photo getPo() {
    return po;
    } public void setPo(Photo po) {
    this.po = po;
    } public String getMsg() {
    return msg;
    } public void setMsg(String msg) {
    this.msg = msg;
    } public void setMyFileContentType(String contentType) {
    this.contentType = contentType;
    } public void setMyFileFileName(String fileName) {
    System.out.println("fileName>>>>>>>>>>>>>>>>" + fileName);
    this.fileName = fileName;
    } public void setMyFile(File myFile) {
    this.myFile = myFile;
    }
    /**
     * 上传文件时IO流操作(上传时所需函数1)
     * @param src 表单域接收的源文件
     * @param dst 上传的文件保存地址
     * 
     * */
    private static boolean copy(File src, File dst) {
    try {
    InputStream in = null;
    OutputStream out = null;
    try {
    in = new BufferedInputStream(new FileInputStream(src),
    BUFFER_SIZE);
    out = new BufferedOutputStream(new FileOutputStream(dst),
    BUFFER_SIZE);
    byte[] buffer = new byte[BUFFER_SIZE];
    while (in.read(buffer) > 0) {
    out.write(buffer);
    }
    } finally {
    if (null != in) {
    in.close();
    }
    if (null != out) {
    out.close();
    }
    }
    } catch (Exception e) {
    e.printStackTrace();
    System.out.println("文件保存时发生错误>>>>>>>"+e.getMessage());
    return false;
    }
    return true;
    }
    /**
     * 获取上传文件的扩展名(上传时所需函数2)
     * @param fileName 上传文件的文件名,该文件名不包括文件的路径
     * @return 扩展名(String)
     * */
    private static String getExtention(String fileName) {
    System.out.println("fileName>>>>>>>>>>>>>>>>" + fileName);
    int pos = fileName.lastIndexOf(".");
    return fileName.substring(pos);
    }

    @SuppressWarnings("static-access")
    @Action(value = "/upload", results = { @Result(name = SUCCESS, location = "/success.jsp") }, interceptorRefs = { @InterceptorRef("fileUploadStack") })
    public String upload()throws Exception{
    //由系统时间生成的文件名,数据库保存的文件名
    String imageFileName = new Date().getTime() + getExtention(fileName);
    //File imageFile = new File(ServletActionContext.getServletContext().getRealPath("/UploadImages") + "/" + imageFileName);
    File imageFile = new File(this._resourcePath + "/user/" + imageFileName);
    if(copy(myFile, imageFile)){
    Photo p=new Photo();
    p.setPhotoName(imageFileName);
    p.setAddTime(UtilTools.getDate());
    p.setDescribes(po.getDescribes());
    p.setUploaderId(1);
    userPhotoService.addPhoto(p);
    msg="上传成功!";
    return SUCCESS;
    }else{
    msg="上传失败!";
    return "fail";
    }
    }}
      

  13.   

    误导大家了~其实不用配置拦截器~是我struts.xml中的临时保存目录不存在~配置对了就好了~对不起啊~