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

struts2文件下载

2008-11-25 14:18 381 查看
下面是jsp文件的代码:

<%@ page language="java" import="java.io.*" pageEncoding="GBK"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>My JSP 'down.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

</head>

<body>

<%

//取得服务器"/download"目录的物理路径

String path = request.getRealPath("/download");

//取得"/download/file"目录的file对象

File file = new File(path);

//取得file目录下所有文件

File[] files = file.listFiles();

for (int i = 0; i < files.length; i++) {

String fname = files[i].getName();

//对文件名进行url编码(UTF-8指明fname原来的编码,UTF-8一般由本地编码GBK代替)

fname = java.net.URLEncoder.encode(fname, "UTF-8");

out.println("<a href=download.action?name=" + fname + ">"

+ files[i].getName() + "</a><br>");

}

%>

</body>

</html>

struts.xml相应的Action配置:

<action name="download" class="com.hxz.action.DownloadAction">

<result name="success" type="stream">

<param name="contentType">application/rar</param>

<param name="inputName">targetFile</param>

<param name="contentDisposition">attachment;filename="${fileName}"</param>

<param name="bufferSize">4096</param>

</result>

</action>

DownloadAction

package com.hxz.action;

import java.io.InputStream;

import java.io.UnsupportedEncodingException;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")

public class DownloadAction extends ActionSupport {

private String fileName;

public void setFileName(){

//得到请求下载的文件名

String fname=ServletActionContext.getRequest().getParameter("name");

try {

/*

* 对fname参数进行UTF-8解码,注意:实际进行UTF-8解码时会使用本地编码,本机为GBK。

* 这里使用request.setCharacterEncoding解码无效.

* 只有解码了getTargetFile()方法才能在下载目录下正确找到请求的文件

* */

fname = new String(fname.getBytes("ISO-8859-1"), "UTF-8");

} catch (Exception e) {

e.printStackTrace();

}

this.fileName=fname;

System.out.println(fileName);

}

/*

* @getFileName

* 此方法对应的是struts.xml文件中的:

* <param name="contentDisposition">attachment;filename="${fileName}"</param>

* 这个属性设置的是下载工具下载文件时显示的文件名,

* 要想正确的显示中文文件名,我们需要对fileName再次编码

* 否则中文名文件将出现乱码,或无法下载的情况

* */

public String getFileName() throws UnsupportedEncodingException {

fileName=new String(fileName.getBytes(),"ISO-8859-1");

return fileName;

}

public InputStream getTargetFile()throws Exception{

this.setFileName();

return ServletActionContext.getServletContext().getResourceAsStream(("/download/" + fileName));

}

public String execute()throws Exception{

return SUCCESS;

}

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