Struts2实现文件上传和下载

 

当进行文件上传时,表单提交方法必须为Post方法,enctype必须为multipart/form-data

例如:

 

<form action="FileUploadServlet" method = "post" enctype="multipart/form-data">
    	<input type = "file" name = "file"><br/>
    	<input type = "submit" value = "submit">
    </form>

 然后采用fileUpload插件中的类进行请求解析(上传文件的内容放在Post,即可通过解析获取其内容)。

 

Servlet的解析:

 

@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException
	{
		try
		{
			String filePath = req.getServletContext().getRealPath("/files");
			File file = new File(filePath);
			DiskFileItemFactory dfif = new DiskFileItemFactory(1024 * 1024,file);
			ServletFileUpload fileUpload = new ServletFileUpload(dfif);
			//返回的是FileItem的集合
			List<FileItem> list = (List<FileItem>) fileUpload.parseRequest(req);
			for (int i = 0; i < list.size(); i++)
			{
				FileItem fi = list.get(i);
				if (fi.isFormField())
				{
					// 非文件的表单。
				}
				else
				{
fi.write(new File(filePath+ "/"+ 
new String(fi.getName().getBytes("iso8859-1"),"iso8859-1")));
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

 

 采用Struts2进行解析:

 

package com.dong.struts2;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport
{
	private String username;
	private List<File> file;
	private List<String> fileFileName;
	private List<String> fileContentType;
	public String getUsername()
	{
		return username;
	}
	public void setUsername(String username)
	{
		this.username = username;
	}
	public List<File> getFile()
	{
		return file;
	}
	public void setFile(List<File> file)
	{
		this.file = file;
	}
	public List<String> getFileFileName()
	{
		return fileFileName;
	}
	public void setFileFileName(List<String> fileFileName)
	{
		this.fileFileName = fileFileName;
	}
	public List<String> getFileContentType()
	{
		return fileContentType;
	}
	public void setFileContentType(List<String> fileContentType)
	{
		this.fileContentType = fileContentType;
	}
	@Override
	public String execute() throws Exception
	{
		String filePath = ServletActionContext.getServletContext().getRealPath("/files");
		for (int i = 0; i < file.size(); i++)
		{
			FileInputStream fin = new FileInputStream(file.get(i));
			FileOutputStream fos = new FileOutputStream(new File(filePath + "/"
					+ fileFileName.get(i)));
			byte[] temp = new byte[521];
			int length = 0;
			while (-1 != (length = fin.read(temp)))
			{
				fos.write(temp, 0, length);
			}
			fin.close();
			fos.close();
		}
		return SUCCESS;
	}
}

 

 其中变量的定义根据如下文档:

FileUploadInterceptor.java

下面是其帮助文档中的部分解释:

Interceptor that is based off of MultiPartRequestWrapper, which is automatically applied for any request that includes a file. It adds the following parameters, where [File Name] is the name given to the file uploaded by the HTML form:

[File Name] : File - the actual File

[File Name]ContentType : String - the content type of the file

[File Name]FileName : String - the actual name of the file uploaded (not the HTML name)

 

 

文件下载:

平常而言,只需要将文件连接到文件的路径即可。但是对于有些可读文件,例如:txt、图片等文件,浏览器会自动将其显示在页面里,而不是弹出一个下载对话框。那么我们可以在Struts2struts2.xml中进行配置。

下面的示例:

Jsp中的代码:

 

<body>
    <a href = "fileDownload.action">txt文档</a><br/>
    <a href = "./files/securecrt.zip">ppt文档</a>
  </body>
Struts.xml中的配置:
<action name="fileDownload" class="com.dong.struts2.FileDownLoadAction">
			<result name="success" type="stream">
				<param name="inputName">txtFile</param>
				<param name="contentDisposition">attachment;filename="hs.txt"</param>
			</result>
		</action>
对应的com.dong.struts2.FileDownLoadAction中的代码:
package com.dong.struts2;
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileDownLoadAction extends ActionSupport
{
	public InputStream getTxtFile()
	{
		return ServletActionContext.getServletContext().getResourceAsStream("files/www.pudn.com.txt");
	}
	@Override
	public String execute() throws Exception
	{
		return SUCCESS;
	}
} 

则可以完成一个文本文件的下载。其中XML中的配置参看StreamResult.java(org.apache.struts2.dispatcher.StreamResult)中的代码。

其中各个param的含义如下:

This result type takes the following parameters:

contentType - the stream mime-type as sent to the web browser (default = text/plain).

contentLength - the stream length in bytes (the browser displays a progress bar).

contentDisposition - the content disposition header value for specifing the file name (default = inline, values are typically attachment;filename="document.pdf".

inputName - the name of the InputStream property from the chained action (default = inputStream).

bufferSize - the size of the buffer to copy from input to output (default = 1024).

allowCaching if set to 'false' it will set the headers 'Pragma' and 'Cache-Control' to 'no-cahce', and prevent client from caching the content. (default = true)

contentCharSet if set to a string, ';charset=value' will be added to the content-type header, where value is the string set. If set to an expression, the result of evaluating the expression will be used. If not set, then no charset will be set on the header

帮助文档中提供的示例:

 

Example:

<result name="success" type="stream">
   <param name="contentType">image/jpeg</param>
   <param name="inputName">imageStream</param>
   <param name="contentDisposition">attachment;filename="document.pdf"</param>
   <param name="bufferSize">1024</param>
 </result> 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值