Struts2实现文件上传


文件上传这个功能是很多网站都要有的,当然,Struts对文件上传也进了支持,可以说,使用Struts实现文件上传是非常简单的而且方便,下面来介绍一下。

首先,需要导入包commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar,后面的那个包是因为在下面的代码中会使用到它里面的一些方法,实际上也可以不加入,这些包都是可以在Struts的lib文件夹里面找到的.

然后就是写Action类了,这里需要接收文件(File类型),文件名,文件类型,文件名必须和表单里面的name属性名一致,学过servlet的都知道为什么,然后文件名的写法是文件名+FileName,然后文件类型名称的写法是文件名+ContentType,分别把他们设置成属性,就是分别为他们提供set和get方法。

接着需要把接受到的File文件转存到服务器的目录里,否则它就存放在Struts的临时目录里面,在Action执行完毕后会被删除。具体方法是使用servletContextgetRealPath方法获得项目的绝对路径,然后建立一个目录去存放这个上传的文件。

代码如下

  1. package com.bird.action;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5.   
  6. import org.apache.commons.io.FileUtils;  
  7. import org.apache.struts2.ServletActionContext;  
  8.   
  9. public class FileUpload {  
  10.       
  11.     private File image;//获取上传文件   
  12.     private String imageFileName;//获取上传文件名称   
  13.     private String imageContentType;//获取上传文件类型   
  14.       
  15.     public String getImageContentType() {  
  16.         return imageContentType;  
  17.     }  
  18.   
  19.     public void setImageContentType(String imageContentType) {  
  20.         this.imageContentType = imageContentType;  
  21.     }  
  22.   
  23.     public File getImage() {  
  24.         return image;  
  25.     }  
  26.   
  27.     public void setImage(File image) {  
  28.         this.image = image;  
  29.     }  
  30.   
  31.     public String getImageFileName() {  
  32.         return imageFileName;  
  33.     }  
  34.   
  35.     public void setImageFileName(String imageFileName) {  
  36.         this.imageFileName = imageFileName;  
  37.     }  
  38.   
  39.     public String execute(){  
  40.         String path = ServletActionContext.getServletContext().getRealPath("/images");  
  41.           
  42.         System.out.println(path);  
  43.         if(image != null){  
  44.         File savefile = new File(new File(path),imageFileName);  
  45.         if(!savefile.getParentFile().exists())  
  46.             savefile.getParentFile().mkdirs();  
  47.         try {  
  48.             FileUtils.copyFile(image , savefile);  
  49.         } catch (IOException e) {  
  50.             // TODO Auto-generated catch block   
  51.             e.printStackTrace();  
  52.         }  
  53.           
  54.         String[] t = imageContentType.split("/");  
  55.         for(String s : t)  
  56.             System.out.println(s);  
  57.         }  
  58.         return "success";  
  59.     }  
  60. }  
  • 1
  • 2
  • 下一页

相关内容