`

struts2 文件的上传和下载

 
阅读更多

1 使用struts2进行文件的上传和下载十分的简单,不是再像jsp和servlet中那么麻烦。

  现在说一下,如果以后我们在工作中,遇到一些组件我们不会开发,我们可以通过这种方式进行开发。

  我们打开这个拦截器 fileUpload,然后我们查看这个拦截器的源码,然后我们打开javaDoc这个view,

  收先我们需要在浏览器端进行一些设置,也就是在jsp页面进行一些设置。

            1.method=post
            2.<input type="file" name="xx">
            3.encType="multipart/form-data";

 

 

 

 

Example code: 


 
 <action name="doUpload" class="com.example.UploadAction">
     <interceptor-ref name="fileUpload"/>
     <interceptor-ref name="basicStack"/>
     <result name="success">good_result.jsp</result>
 </action>
 
 

 

You must set the encoding to multipart/form-data in the form where the user selects the file to upload. 

 


 
   <s:form action="doUpload" method="post" enctype="multipart/form-data">
       <s:file name="upload" label="File"/>
       <s:submit/>
   </s:form>
 
 

And then in your action code you'll have access to the File object if you provide setters according to the naming convention documented in the start. 


 
    package com.example;

    import java.io.File;
    import com.opensymphony.xwork2.ActionSupport;

    public UploadAction extends ActionSupport {
       private File file;
       private String contentType;
       private String filename;

       public void setUpload(File file) {
          this.file = file;
       }

       public void setUploadContentType(String contentType) {
          this.contentType = contentType;
       }

       public void setUploadFileName(String filename) {
          this.filename = filename;
       }

       public String execute() {
          //...
          return SUCCESS;
       }
  }

   上面就是官方给出的文档,我们在action中给出相应的Action属性,要求属性名称必须要相同。

  我们根据官方给出的文档,我们首先在webRoot下面创建一个images的文件夹。

publicclass UploadAction extends ActionSupport{
    
    private File image; //上传的文件
private String imageFileName; //文件名称
private String imageContentType; //文件类型

    public String execute() throws Exception {
        String realpath = ServletActionContext.getServletContext().getRealPath("/images");
        //D:\apache-tomcat-6.0.18\webapps\struts2_upload\images
        System.out.println("realpath: "+realpath);
        if (image !=null) {
            File savefile =new File(new File(realpath), imageFileName);
            if (!savefile.getParentFile().exists())
                savefile.getParentFile().mkdirs();
            FileUtils.copyFile(image, savefile);
            ActionContext.getContext().put("message", "文件上传成功");
        }
        return"success";
    }

    public File getImage() {
        return image;
    }

    publicvoid setImage(File image) {
        this.image = image;
    }

    public String getImageFileName() {
        return imageFileName;
    }

    publicvoid setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }

    public String getImageContentType() {
        return imageContentType;
    }

    publicvoid setImageContentType(String imageContentType) {
        this.imageContentType = imageContentType;
    }

    

   然后就可以实现文件的长窗操作了。

  

   下面我详细说一下struts2如何实现多文件的上传操作。

   其实很简单,我们只需把之前注入的属性改成一个集合就好了

  

public class UploadAction extends ActionSupport {

	// 在action类中需要声明三个属性
	private List<File> upload;
	private List<String> uploadContentType;
	private List<String> uploadFileName;

	public List<File> getUpload() {
		return upload;
	}

	public void setUpload(List<File> upload) {
		this.upload = upload;
	}

	public List<String> getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(List<String> uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public List<String> getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(List<String> uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	@Override
	public String execute() throws Exception {

		for (int i = 0; i < upload.size(); i++) {
			
			
			System.out.println("上传文件的类型:" + uploadContentType.get(i));
			System.out.println("上传文件的名称:" + uploadFileName.get(i));

			// 完成文件上传.
			FileUtils.copyFile(upload.get(i), new File("d:/upload", uploadFileName.get(i)));
		}
		return null;
	}

}

 

 

下面我们说一下文件的下载。

1 首先我们说一下前台页面,前台页面一张是英文名称的txt文档,一个是中文名称的图片

 

<body>
	<a href="${pageContext.request.contextPath}/download?filename=a.txt">a.txt</a>
	<br>
	<a href="${pageContext.request.contextPath}/download?filename=捕获.png">捕获.png</a>
	<br>
</body>

  

public class DownloadAction extends ActionSupport {

	private String filename; // 要下载文件的名称

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	// 设置下载文件mimeType类型
	public String getContentType() {

		String mimeType = ServletActionContext.getServletContext().getMimeType(
				filename);
		return mimeType;
	}

	// 获取下载文件名称
	public String getDownloadFileName() throws UnsupportedEncodingException {

		return DownloadUtils.getDownloadFileName(ServletActionContext
				.getRequest().getHeader("user-agent"), filename);

	}

	public InputStream getInputStream() throws FileNotFoundException,
			UnsupportedEncodingException {

		filename = new String(filename.getBytes("iso8859-1"), "utf-8"); // 解决中文名称乱码.

		FileInputStream fis = new FileInputStream("d:/upload/" + filename);
		return fis;
	}

	@Override
	public String execute() throws Exception {
		System.out.println("进行下载....");
		return SUCCESS;
	}

}

   

public class DownloadUtils {

	public static String getDownloadFileName(String agent, String filename) 
throws UnsupportedEncodingException {
		if (agent.contains("MSIE")) {
			// IE浏览器
			filename = URLEncoder.encode(filename, "utf-8");

		} else if (agent.contains("Firefox")) {
			// 火狐浏览器
			BASE64Encoder base64Encoder = new BASE64Encoder();
			filename = "=?utf-8?B?"
					+ base64Encoder.encode(filename.getBytes("utf-8"))
 + "?=";
		} else {
			// 其它浏览器
			filename = URLEncoder.encode(filename, "utf-8");
		}

		return filename;
	}
}

 

<action name="download" class="cn.itcast.action.DownloadAction">
<result type="stream">
<param name="contentType">${contentType}</param> <!-- 调用当前action中的
getContentType()方法 -->
<param name="contentDisposition">attachment;filename=${downloadFileName}</param>
<param name="inputStream">${inputStream}</param><!-- 调用当前action中的getInputStream()
方法 -->
</result>
</action>

   下面让我进行详细的讲解,首先我们需要在一个超链接中传递下载文件的名称参数,但是如果我们下载的文件是中文的,那么后台接收的时候必须乱码,我们需要根据浏览器的不同进行相应的解析,那个下载的工具类就是我们进行解析的。其次,我们在struts2 的xml的配置文件中,进行相应的配置,我们使用ognl表达式,在这个action中,得到相应的参数,也就是在action中运行相应的方法,我们就可以得到这个相应的对象

当我们点击链接的时候,就可以完成下载。

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics