你好,游客 登录 注册 搜索
背景:
阅读新闻

Struts2文件上传的运行过程实现

[日期:2012-07-30] 来源:Linux社区  作者:jimmy5z [字体:大 中 小]

3.逻辑实现

package com.tarena.dang.user.action;

import java.io.*;

import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.tarena.dang.domain.User;
import com.tarena.dang.user.service.UserService;
import com.tarena.dang.user.service.UserServiceImpl;
/**
 * 注册页面的Action控制器业务实现
 * @author JimmyZhang
 *
 */
public class RegisterAction {
 private UserService userService;
 //使用实体对象简化与表单元素对应关系
 private User user;
 private String vcode;
 //定义与文件域upload赌赢的属性
 private File upload;//上传文件
 private String uploadFileName;//上传文件的文件名
 private String uploadContentType;//上传文件类型
 public String getVcode() {
  return vcode;
 }
 public void setVcode(String vcode) {
  this.vcode = vcode;
 }
 public User getUser() {
  return user;
 }
 public void setUser(User user) {
  this.user = user;
 }
 public RegisterAction(){
  userService = new UserServiceImpl();
  System.out.println("【RegisterAction】调用默认无参构造方法");
 }
 
 
 public String execute() throws Exception{
  //判断用户输入的验证与session中是否一直一致
  ActionContext ac = ActionContext.getContext();
  String session_vocode = (String)ac.getSession().get("vcode");
  if(!vcode.equals(session_vocode)){
   ac.put("vcode_info", "<img src='/dang/images/wrong.gif'/>验证码不匹配");
   return "input";
  }
  boolean isSuccess = userService.register(user);
  if(isSuccess){
   //上传头像,File upload-->/images/user/userName.jpg
   //得到服务器端的物理路径
   String path = ServletActionContext
     .getServletContext().getRealPath("/images/user/"+user.getUserName()+".jpg");
   //创建服务器端文件的File对象
   File dest = new File(path);
   //upload-->dest
   InputStream fis = new FileInputStream(upload);
   OutputStream fos = new FileOutputStream(dest);
   byte[] b = new byte[1024];
   int n;
   while((n=fis.read(b,0,b.length))!=-1){
    fos.write(b,0,n);   
   }
   fos.close();
   fis.close();
   //注册成功
   ac.put("user", user);
   return "ok";
  }else{
   return "input";
  }
 
 }
 public File getUpload() {
  return upload;
 }
 public void setUpload(File upload) {
  this.upload = upload;
 }
 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;
 }

 
 
}

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款