请教个问题~谢谢啦!

l3eta28 2009-12-18 03:05:30
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)


...全文
255 26 打赏 收藏 转发到动态 举报
写回复
用AI写文章
26 条回复
切换为时间正序
请发表友善的回复…
发表回复
dgdlxh 2009-12-21
  • 打赏
  • 举报
回复
看的有点晕
l3eta28 2009-12-21
  • 打赏
  • 举报
回复
[Quote=引用 20 楼 zys2419740 的回复:]
chinaas.member.action.userPhoto.UserPhotoAction.uploadPhoto(UserPhotoAction.java:46)  这是哪一行啊?
[/Quote]
和那个没关系的~是拦截器的问题~
zys2419740 2009-12-21
  • 打赏
  • 举报
回复
chinaas.member.action.userPhoto.UserPhotoAction.uploadPhoto(UserPhotoAction.java:46) 这是哪一行啊?
l3eta28 2009-12-21
  • 打赏
  • 举报
回复
谢谢各位了~我想就应该是拦截器的问题~等我研究好后,发给你们~
chht108 2009-12-21
  • 打赏
  • 举报
回复
不太懂
l3eta28 2009-12-21
  • 打赏
  • 举报
回复
误导大家了~其实不用配置拦截器~是我struts.xml中的临时保存目录不存在~配置对了就好了~对不起啊~
l3eta28 2009-12-21
  • 打赏
  • 举报
回复

@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";
}
}

}
l3eta28 2009-12-21
  • 打赏
  • 举报
回复
@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";
}
}

}
这个是最终的正确结果~
SambaGao 2009-12-19
  • 打赏
  • 举报
回复
//SavePath
private String SavePath ;
ServletActionContext.getRequest().getRealPath(SavePath) ;

再Struts的配置文件中
上传文件拦截器
<param name="SavePath">/upload</param>

<<项目实践精解>>梁立新的书上就有参考一下。
fanma 2009-12-19
  • 打赏
  • 举报
回复
chinaas.member.action.userPhoto.UserPhotoAction.uploadPhoto(UserPhotoAction.java:46)

UserPhotoAction 这个类看看.
SambaGao 2009-12-19
  • 打赏
  • 举报
回复
我感觉应该是文件上传到服务器里路径的问题。
以前也遇到过这种问题。

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


dongyangmoney 2009-12-19
  • 打赏
  • 举报
回复
注解,很简单看看就可以
handsome_huxiulei 2009-12-19
  • 打赏
  • 举报
回复
annotation不详
JavaAlpha 2009-12-19
  • 打赏
  • 举报
回复
chinaas.member.action.userPhoto.UserPhotoAction.uploadPhoto(UserPhotoAction.java:46)
这一行的代码是什么?
liuahuilele 2009-12-19
  • 打赏
  • 举报
回复
[Quote=引用 17 楼 pasterzhang 的回复:]
System.out.println(">>>>>>>>>>>>>>>>>>"+ServletActionContext.getRequest().getRealPath("/upload")); 就这个路径错了 ,建议先改个物理路径试试 . 还有你用的什么上传组件 建议使用 upload 的jar包 这样容易些 开发效率也会大大提高
[/Quote]
试试先
pasterzhang 2009-12-19
  • 打赏
  • 举报
回复
System.out.println(">>>>>>>>>>>>>>>>>>"+ServletActionContext.getRequest().getRealPath("/upload")); 就这个路径错了 ,建议先改个物理路径试试 . 还有你用的什么上传组件 建议使用 upload 的jar包 这样容易些 开发效率也会大大提高
zhanlang9075 2009-12-19
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 dreamstyle 的回复:]
不熟习注解
[/Quote]
来学习一下!
keepkey 2009-12-19
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 crazylaa 的回复:]
不要注解能否取到文件?先保证不要注解能取到,再变注解。struts文件上传本来就有点麻烦的,何况你这里看起来似乎是个文件列表。。。。
[/Quote]

也通宵?
crazylaa 2009-12-19
  • 打赏
  • 举报
回复
不要注解能否取到文件?先保证不要注解能取到,再变注解。struts文件上传本来就有点麻烦的,何况你这里看起来似乎是个文件列表。。。。
zl3450341 2009-12-18
  • 打赏
  • 举报
回复
注解不太熟
帮顶下
加载更多回复(6)

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧