Struts2实现文件的上传

struts2实现文件上传

需要导入的jar包

commons-io

commons-fileupload

需要使用FileUpload拦截器

表单中首先注意:form中声明

  enctype="multipart/form-data"       method="post"

在后台的action中声明三个参数

private File [file]; //file和表单中 type="file"的name值相同

private String [file]contentType; //文件的类型

private String [file]FileName;  //文件的名称

生成Setter和Getter方法

使用流对文件进行读写操作

核心代码如下 

  ServletContext context = ServletActionContext.getServletContext();
  String path = context.getRealPath("/upload/"+pptFileName);
  System.out.println(path);
  FileInputStream in = new FileInputStream(ppt);
  FileOutputStream out = new FileOutputStream(path);
  byte[] buffer = new byte[1024];
  int len = 0;
  while((len = in.read(buffer))!=-1){
  out.write(buffer,0, len);
  }
  out.close();
  in.close();

 

posted @ 2018-01-16 22:57  森宇旅人  阅读(100)  评论(0)    收藏  举报