struts文件下载 请教各位: 如何实现struts文件下载功能 请把代码贴出来 谢谢~! 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 下载很简单,直接用SERVLET就实现了,现在给出例子: 你上传,肯定得到了路径和名字,那么这里直接这样: /******************加到web.xml**********************/ <servlet> <servlet-name>webdownload</servlet-name> <servlet-class>zymms.commons.WebDownLoad</servlet-class> </servlet> <servlet-mapping> <servlet-name>webdownload</servlet-name> <url-pattern>/servlet/webdownload</url-pattern> </servlet-mapping> /******************注意***************************/ 调用时,../servlet/webdownload/fn=路径+文件名 /************************************************/ webdownload.java文件如下: package zymms.commons; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** * * <p>Title: </p> * <p>Description:下载文件servlet类 </p> * <p>Copyright: Copyright (c) 2006</p> * <p>Company: Summit Software Co.,Ltd</p> * @author * @version 1.0 */ public class WebDownLoad extends HttpServlet { public WebDownLoad() { } private ServletConfig config; public void init(ServletConfig config) throws ServletException { super.init(config); this.config = config; } public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException { doGet(req,res); } public static String getAttachName(String file_name) { if(file_name==null) return ""; file_name = file_name.trim(); int iPos = 0; iPos = file_name.lastIndexOf("\\"); if(iPos>-1){ file_name = file_name.substring(iPos+1); } iPos = file_name.lastIndexOf("/"); if(iPos>-1){ file_name = file_name.substring(iPos+1); } iPos = file_name.lastIndexOf(File.separator); if(iPos>-1){ file_name = file_name.substring(iPos+1); } return file_name; } public static String toUtf8String(String s) { StringBuffer sb = new StringBuffer(); for (int i=0;i<s.length();i++) { char c = s.charAt(i); if (c >= 0 && c <= 255) { sb.append(c); } else { byte[] b; try { b = Character.toString(c).getBytes("utf-8"); } catch (Exception ex) { System.out.println(ex); b = new byte[0]; } for (int j = 0; j < b.length; j++) { int k = b[j]; if (k < 0) k += 256; sb.append("%" + Integer.toHexString(k).toUpperCase()); } } } String s_utf8 = sb.toString(); sb.delete(0,sb.length()); sb.setLength(0); sb = null; return s_utf8; } private String getRealName(HttpServletRequest request,String file_name) { if(request==null || file_name==null) return null; file_name = file_name.trim(); if(file_name.equals("")) return null; String file_path = request.getRealPath(file_name); if ( file_path== null) return null; File file = new File(file_path); if (!file.exists()) return null; return file_path; } public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException { String file_name = request.getParameter("fn"); if(file_name==null) file_name = ""; file_name = file_name.trim(); InputStream inStream= null; String attch_name = ""; byte[] b = new byte[100]; int len= 0; try { //取得附件的名称 attch_name = getAttachName(file_name); file_name = getRealName(request,file_name); if(file_name==null) { response.sendRedirect("/pms/frame/error_404.jsp"); System.out.println("文件不存在,或者禁止下载"); return ; } attch_name = toUtf8String(attch_name); //读到流中 inStream=new FileInputStream(file_name); //设置输出的格式 response.reset(); response.setContentType("application/x-msdownload"); response.addHeader("Content-Disposition","attachment; filename=\"" + attch_name + "\""); //循环取出流中的数据 while((len=inStream.read(b)) >0) { response.getOutputStream().write(b,0,len); } inStream.close(); }catch ( Exception e ){ if ( e instanceof java.io.FileNotFoundException ) { try { response.sendRedirect("/tip/file_not_found.html"); } catch ( IOException ex ) { ex.printStackTrace(System.err); } } else { e.printStackTrace(System.err); } } } } Struts中DownloadAction的使用 1.自从Struts 1.2.6版本,就出现了DownloadAction类,主要就是用于处理web应用的下载。 使用DownloadAction也是很简单的。 2.自定义的Action继承DownloadAction。 然后实现:getStreamInfo()方法,该方法用于返回文件或者流的信息。 protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) 可以覆盖:getBufferSize方法,用于自定义向servlet的output stream传输数据的缓冲区大小(bytes字节数)。 DownloadAction中有一个内部的接口StreamInfo代表着不同流的抽象信息,定义了两个方法, public static interface StreamInfo { public abstract String getContentType();//得到下载文件的MIME类型 public abstract InputStream getInputStream() throws IOException; } 其中DownloadAction提供了两个StreamInfo的默认实现: FileStreamInfo 代表从磁盘下载一个文件 ResourceStreamInfo 代表下载一个web应用中的一个资源 当然,我们自己还可以实现自己特定的类,比如从数据库中取得流的类,或者从FTP取得文件的流的类。 下面写一个简单的覆盖getStreamInfo的方法,实现下载Web应用的/images/bbg.gif图片: public StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ response.setHeader("Content-disposition", "attachment; filename=" + "bbg2.gif");//设置文件名称 StreamInfo si = new ResourceStreamInfo("image/gif",this.servlet.getServletContext(),"/images/bbg.gif"); return si; } 使用非常方便,而且能够保持程序一致的结构。原来我开发的系统中下载都是统一使用Servlet的,由于项目中整合了Spring,所以对于Servlet还需要单独的方法来获取相应的服务层的Bean,使用DownloadAction之后,所有的Action都是由Spring进行管理的,非常方便。 上面有两种方法,一种是基本的servlet方法,你只要稍加修改就可以了第二种是使用 Struts中DownloadAction,你参考一下 数据库错误…… 一个关于上传文件用的工具类的思考,到底用静态方法好呢还是不用? 分页的问题~! 新手提问 请问两个Web系统,UTF-8、GB2312的中文传递问题 JSTL问题 参数传递?? 关于javx.servlet,如何找到此package? 急问!!:如何用一个servlet接受请求后,改变请求的参数值后调用另一个servlet myeclipse如何点ctrl+F11自动出来浏览器呢? Java Web开发中连接数据库主要用什么方式? jsp如何使用文件上传(如视频,文件,图片)
你上传,肯定得到了路径和名字,那么这里直接这样:
/******************加到web.xml**********************/
<servlet>
<servlet-name>webdownload</servlet-name>
<servlet-class>zymms.commons.WebDownLoad</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>webdownload</servlet-name>
<url-pattern>/servlet/webdownload</url-pattern>
</servlet-mapping>
/******************注意***************************/
调用时,../servlet/webdownload/fn=路径+文件名
/************************************************/
webdownload.java文件如下:
package zymms.commons;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
*
* <p>Title: </p>
* <p>Description:下载文件servlet类 </p>
* <p>Copyright: Copyright (c) 2006</p>
* <p>Company: Summit Software Co.,Ltd</p>
* @author
* @version 1.0
*/
public class WebDownLoad extends HttpServlet {
public WebDownLoad() {
}
private ServletConfig config;
public void init(ServletConfig config) throws ServletException {
super.init(config);
this.config = config;
}
public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException {
doGet(req,res);
}
public static String getAttachName(String file_name) {
if(file_name==null) return "";
file_name = file_name.trim();
int iPos = 0;
iPos = file_name.lastIndexOf("\\");
if(iPos>-1){
file_name = file_name.substring(iPos+1);
}
iPos = file_name.lastIndexOf("/");
if(iPos>-1){
file_name = file_name.substring(iPos+1);
}
iPos = file_name.lastIndexOf(File.separator);
if(iPos>-1){
file_name = file_name.substring(iPos+1);
}
return file_name;
}
public static String toUtf8String(String s) {
StringBuffer sb = new StringBuffer();
for (int i=0;i<s.length();i++) {
char c = s.charAt(i);
if (c >= 0 && c <= 255) {
sb.append(c);
} else {
byte[] b;
try {
b = Character.toString(c).getBytes("utf-8");
} catch (Exception ex) {
System.out.println(ex);
b = new byte[0];
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0) k += 256;
sb.append("%" + Integer.toHexString(k).toUpperCase());
}
}
}
String s_utf8 = sb.toString();
sb.delete(0,sb.length());
sb.setLength(0);
sb = null;
return s_utf8;
}
private String getRealName(HttpServletRequest request,String file_name) {
if(request==null || file_name==null) return null;
file_name = file_name.trim();
if(file_name.equals("")) return null;
String file_path = request.getRealPath(file_name);
if ( file_path== null) return null;
File file = new File(file_path);
if (!file.exists()) return null;
return file_path;
}
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException {
String file_name = request.getParameter("fn");
if(file_name==null) file_name = "";
file_name = file_name.trim();
InputStream inStream= null;
String attch_name = "";
byte[] b = new byte[100];
int len= 0;
try {
//取得附件的名称
attch_name = getAttachName(file_name);
file_name = getRealName(request,file_name);
if(file_name==null) {
response.sendRedirect("/pms/frame/error_404.jsp");
System.out.println("文件不存在,或者禁止下载");
return ;
}
attch_name = toUtf8String(attch_name);
//读到流中
inStream=new FileInputStream(file_name);
//设置输出的格式
response.reset();
response.setContentType("application/x-msdownload");
response.addHeader("Content-Disposition","attachment; filename=\"" + attch_name + "\"");
//循环取出流中的数据
while((len=inStream.read(b)) >0) {
response.getOutputStream().write(b,0,len);
}
inStream.close();
}catch ( Exception e ){
if ( e instanceof java.io.FileNotFoundException ) {
try {
response.sendRedirect("/tip/file_not_found.html");
}
catch ( IOException ex ) {
ex.printStackTrace(System.err);
}
}
else {
e.printStackTrace(System.err);
}
}
}
}
1.自从Struts 1.2.6版本,就出现了DownloadAction类,主要就是用于处理web应用的下载。
使用DownloadAction也是很简单的。
2.自定义的Action继承DownloadAction。
然后实现:getStreamInfo()方法,该方法用于返回文件或者流的信息。
protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
可以覆盖:getBufferSize方法,用于自定义向servlet的output stream传输数据的缓冲区大小(bytes字节数)。
DownloadAction中有一个内部的接口StreamInfo代表着不同流的抽象信息,定义了两个方法,
public static interface StreamInfo {
public abstract String getContentType();//得到下载文件的MIME类型
public abstract InputStream getInputStream() throws IOException;
}
其中DownloadAction提供了两个StreamInfo的默认实现:
FileStreamInfo 代表从磁盘下载一个文件
ResourceStreamInfo 代表下载一个web应用中的一个资源
当然,我们自己还可以实现自己特定的类,比如从数据库中取得流的类,或者从FTP取得文件的流的类。
下面写一个简单的覆盖getStreamInfo的方法,实现下载Web应用的/images/bbg.gif图片:
public StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response){
response.setHeader("Content-disposition",
"attachment; filename=" + "bbg2.gif");//设置文件名称
StreamInfo si = new ResourceStreamInfo("image/gif",this.servlet.getServletContext(),"/images/bbg.gif");
return si;
}
使用非常方便,而且能够保持程序一致的结构。原来我开发的系统中下载都是统一使用Servlet的,由于项目中整合了Spring,所以对于Servlet还需要单独的方法来获取相应的服务层的Bean,使用DownloadAction之后,所有的Action都是由Spring进行管理的,非常方便。