您的位置:首页 > 编程语言 > Java开发

struts2文件上传

2014-03-22 16:34 113 查看
package com.lovo.action;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import javax.servlet.ServletContext;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;

public class AjaxAction extends ActionSupport implements ServletResponseAware{

private HttpServletResponse response;

private String userName;

private int age;

//定义文件变量,变量名为表单名一致,表示客户端上传文件的数据

private File head;

//定义字符串,变量名为表单名+"FileName",表示文件上传的原始名称

private String headFileName;

public void ajax()throws Exception{

this.response.getWriter().print("ajax测试");

}

public String reg()throws Exception{

System.out.println("用户名" + userName+"年龄"+age);

ServletContext context=ServletActionContext.getServletContext();

//得到文件夹的真是路径

String dirpath=context.getRealPath("/img");

String filename=System.currentTimeMillis()+headFileName.substring(headFileName.lastIndexOf("."));

//创建写入流

OutputStream out=new FileOutputStream(dirpath+"/"+filename);

//创建读取流

InputStream in=new FileInputStream(head);

System.out.println(head);

byte[] by=new byte[1024];

int len=0;

while((len=in.read(by))!=-1){

out.write(by, 0, len);

}

out.flush();

out.close();

return "index";

}

public void setServletResponse(HttpServletResponse arg0) {

this.response=arg0;

this.response.setContentType("text/html;charset=utf-8");

}

@Override

public void validate() {

if(this.userName==null|| !this.userName.matches("[a-zA-Z\\u4e00-\\u9fa5]{2,}")){

this.addFieldError("userName", "用户名最少二位");

}

if(this.age<10||this.age>40){

this.addFieldError("age", "年龄必须在18-40之间");

}

}

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public File getHead() {

return head;

}

public void setHead(File head) {

this.head = head;

}

public String getHeadFileName() {

return headFileName;

}

public void setHeadFileName(String headFileName) {

this.headFileName = headFileName;

}

}

/********************************************************************

jsp页面
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: