在文件下载的时候将其保存而不是直接在浏览器上打开!
2005-04-22 09:16
816 查看
共五个类,分别如下,
package com.netec.util.download;
/**
* <p>Title:download exception </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
public class DowLoadException extends Exception {
public DowLoadException() {
}
public DowLoadException(String p0) {
super(p0);
}
public DowLoadException(Throwable p0) {
super(p0);
}
public DowLoadException(String p0, Throwable p1) {
super(p0, p1);
}
}
package com.netec.util.download;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.io.UnsupportedEncodingException;
import java.io.FileInputStream;
import java.io.*;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
public class DownLoad {
private DownLoad() {
}
public static void donwload(
HttpServletRequest request,
HttpServletResponse response,
String src_fname,
String dst_fname
) throws DowLoadException {
int buffSize=1024*10;//size of buffer for read file
//try {
//Translates the file's name into application/x-www-form-urlencoded format
// dst_fname = URLEncoder.encode(dst_fname, "UTF-8");
//}
// catch (UnsupportedEncodingException ex) {
// throw new DowLoadException("error to encode the file's name ",ex);
//}
response.setContentType("application/octet-stream; charset=GBK");
response.setHeader("Content-disposition", "attachment; filename=/"" + dst_fname + "/"");
FileInputStream fis = null;
try {
fis = new FileInputStream(src_fname);
}
catch (FileNotFoundException ex) {
throw new DowLoadException("source file is not found",ex);
}
BufferedInputStream buffIn=new BufferedInputStream(fis);
byte[] byteBuff=new byte[buffSize];
try {
OutputStream outStream = response.getOutputStream();
BufferedOutputStream buffOut=new BufferedOutputStream(outStream);
int validLength=0;
//carry btye arrary
while((validLength=buffIn.read(byteBuff))!=-1){
buffOut.write(byteBuff,0,validLength);
}
buffOut.flush();
buffOut.close();
buffIn.close();
}
catch (IOException ex) {
throw new DowLoadException("file option error",ex);
}
}
}
package com.netec.util.download.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import com.netec.util.RequestNativeProxy;
import com.netec.util.download.DowLoadException;
import com.netec.util.download.DownLoad;
import java.io.*;
public class DownLoadServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GBK";
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//request proxy deal with "iso-8859-1"cord for getParameter method.
request=new RequestNativeProxy(request);
/*
if(!request.getMethod().trim().equalsIgnoreCase("post")){
throw new ServletException("This request must be /"post/" method. ");
}*/
String src_fname = request.getParameter("src_fname");
String dst_fname = request.getParameter("dst_fname");
//To get whole source file name
src_fname=this.getServletContext().getRealPath(src_fname);
src_fname = src_fname.replace('/',File.separatorChar);
try {
DownLoad.donwload(request, response, src_fname, dst_fname);
}
catch (DowLoadException ex) {
//throw new ServletException(ex);
ex.printStackTrace(System.out);
}
return;
}
//Clean up resources
public void destroy() {
}
}
package com.netec.util;
public class ConversionHtml {
/**
* (Constructor)
*
*/
private ConversionHtml() {
super();
}
public static String StringToHtml(String str) {
String repStr = str;
repStr = repStr.replaceAll("/r/n", "<BR>");
repStr = repStr.replaceAll("/r", "<BR>");
repStr = repStr.replaceAll("/n", "<BR>");
repStr = repStr.replaceAll(" ", " ");
return repStr;
}
public static String HtmlToString(String str) {
String repStr = str;
repStr = repStr.replaceAll("<br>|<BR>|<Br>|<bR>|<br/>|<BR/>", "/r/n");
repStr = repStr.replaceAll(" ", " ");
return repStr;
}
}
package com.netec.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class RequestNativeProxy implements HttpServletRequest {
private HttpServletRequest request;
public RequestNativeProxy(HttpServletRequest request) {
super();
this.request=request;
}
public String getAuthType() {
return request.getAuthType();
}
public Cookie[] getCookies() {
return request.getCookies();
}
public long getDateHeader(String arg0) {
return request.getDateHeader(arg0);
}
public String getHeader(String arg0) {
return request.getHeader(arg0);
}
public Enumeration getHeaders(String arg0) {
return request.getHeaders(arg0);
}
public Enumeration getHeaderNames() {
return request.getHeaderNames();
}
public int getIntHeader(String arg0) {
return request.getIntHeader(arg0);
}
public String getMethod() {
return request.getMethod();
}
public String getPathInfo() {
return request.getPathInfo();
}
public String getPathTranslated() {
return request.getPathTranslated();
}
public String getContextPath() {
return request.getContextPath();
}
public String getQueryString() {
return request.getQueryString();
}
public String getRemoteUser() {
return request.getRemoteUser();
}
public boolean isUserInRole(String arg0) {
return request.isUserInRole(arg0);
}
public Principal getUserPrincipal() {
return request.getUserPrincipal();
}
public String getRequestedSessionId() {
return request.getRequestedSessionId();
}
public String getRequestURI() {
return request.getRequestURI();
}
public StringBuffer getRequestURL() {
return request.getRequestURL();
}
public String getServletPath() {
return request.getServletPath();
}
public HttpSession getSession(boolean arg0) {
return request.getSession(arg0);
}
public HttpSession getSession() {
return request.getSession();
}
public boolean isRequestedSessionIdValid() {
return request.isRequestedSessionIdValid();
}
public boolean isRequestedSessionIdFromCookie() {
return request.isRequestedSessionIdFromCookie();
}
public boolean isRequestedSessionIdFromURL() {
return request.isRequestedSessionIdFromURL();
}
public boolean isRequestedSessionIdFromUrl() {
throw new UnsupportedOperationException();
}
public Object getAttribute(String arg0) {
return request.getAttribute(arg0);
}
public Enumeration getAttributeNames() {
return request.getAttributeNames();
}
public String getCharacterEncoding() {
return request.getCharacterEncoding();
}
public void setCharacterEncoding(String arg0)
throws UnsupportedEncodingException {
request.setCharacterEncoding(arg0);
}
public int getContentLength() {
return request.getContentLength();
}
public String getContentType() {
return request.getContentType();
}
public ServletInputStream getInputStream() throws IOException {
return request.getInputStream();
}
public String getParameter(String arg0) {
try {
if(request.getParameter(arg0)!=null) {
return new String(request.getParameter(arg0).getBytes("ISO-8859-1"));
}else {
return null;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "null"+e.getMessage();
}
}
public Enumeration getParameterNames() {
return request.getParameterNames();
}
public String[] getParameterValues(String arg0) {
String[] values= request.getParameterValues(arg0);
for(int i=0;i<values.length;i++) {
try {
if(values[i]!=null) {
values[i]=new String(values[i].getBytes("ISO-8859-1"));
}else {
values[i]=null;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
values[i]="null"+e.getMessage();
}
}
return values;
}
public Map getParameterMap() {
String newValue;
String oldValue;
String name;
Enumeration names=request.getParameterNames();
Map parameterMap=request.getParameterMap();
while(names.hasMoreElements()) {
name=(String)names.nextElement();
oldValue=(String)parameterMap.get(name);
try {
if(oldValue!=null) {
newValue=new String(oldValue.getBytes("ISO-8859-1"));
}else {
newValue=null;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
newValue="null"+e.getMessage();
}
parameterMap.put(name,newValue);
}
return parameterMap;
}
public String getProtocol() {
return request.getProtocol();
}
public String getScheme() {
return request.getScheme();
}
public String getServerName() {
return request.getServerName();
}
public int getServerPort() {
return request.getServerPort();
}
public BufferedReader getReader() throws IOException {
return request.getReader();
}
public String getRemoteAddr() {
return request.getRemoteAddr();
}
public String getRemoteHost() {
return request.getRemoteHost();
}
public void setAttribute(String arg0, Object arg1) {
request.setAttribute(arg0,arg1);
}
public void removeAttribute(String arg0) {
request.removeAttribute(arg0);
}
public Locale getLocale() {
return request.getLocale();
}
public Enumeration getLocales() {
return request.getLocales();
}
public boolean isSecure() {
return request.isSecure();
}
public RequestDispatcher getRequestDispatcher(String arg0) {
return request.getRequestDispatcher(arg0);
}
public String getRealPath(String arg0) {
throw new UnsupportedOperationException();
}
public int getRemotePort() {
throw new UnsupportedOperationException();
}
public String getLocalName() {
throw new UnsupportedOperationException();
}
public String getLocalAddr() {
throw new UnsupportedOperationException();
}
public int getLocalPort() {
throw new UnsupportedOperationException();
}
}
web.xml 中加如下
<servlet>
<servlet-name>download</servlet-name>
<servlet-class>
com.netec.util.download.servlet.DownLoadServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>download</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
jsp页面如下
<a href="/download?src_fname=XXX.jsp&dst_fname=下载后保存的文件名" />下载</a>
package com.netec.util.download;
/**
* <p>Title:download exception </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
public class DowLoadException extends Exception {
public DowLoadException() {
}
public DowLoadException(String p0) {
super(p0);
}
public DowLoadException(Throwable p0) {
super(p0);
}
public DowLoadException(String p0, Throwable p1) {
super(p0, p1);
}
}
package com.netec.util.download;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.io.UnsupportedEncodingException;
import java.io.FileInputStream;
import java.io.*;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
public class DownLoad {
private DownLoad() {
}
public static void donwload(
HttpServletRequest request,
HttpServletResponse response,
String src_fname,
String dst_fname
) throws DowLoadException {
int buffSize=1024*10;//size of buffer for read file
//try {
//Translates the file's name into application/x-www-form-urlencoded format
// dst_fname = URLEncoder.encode(dst_fname, "UTF-8");
//}
// catch (UnsupportedEncodingException ex) {
// throw new DowLoadException("error to encode the file's name ",ex);
//}
response.setContentType("application/octet-stream; charset=GBK");
response.setHeader("Content-disposition", "attachment; filename=/"" + dst_fname + "/"");
FileInputStream fis = null;
try {
fis = new FileInputStream(src_fname);
}
catch (FileNotFoundException ex) {
throw new DowLoadException("source file is not found",ex);
}
BufferedInputStream buffIn=new BufferedInputStream(fis);
byte[] byteBuff=new byte[buffSize];
try {
OutputStream outStream = response.getOutputStream();
BufferedOutputStream buffOut=new BufferedOutputStream(outStream);
int validLength=0;
//carry btye arrary
while((validLength=buffIn.read(byteBuff))!=-1){
buffOut.write(byteBuff,0,validLength);
}
buffOut.flush();
buffOut.close();
buffIn.close();
}
catch (IOException ex) {
throw new DowLoadException("file option error",ex);
}
}
}
package com.netec.util.download.servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import com.netec.util.RequestNativeProxy;
import com.netec.util.download.DowLoadException;
import com.netec.util.download.DownLoad;
import java.io.*;
public class DownLoadServlet extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GBK";
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//request proxy deal with "iso-8859-1"cord for getParameter method.
request=new RequestNativeProxy(request);
/*
if(!request.getMethod().trim().equalsIgnoreCase("post")){
throw new ServletException("This request must be /"post/" method. ");
}*/
String src_fname = request.getParameter("src_fname");
String dst_fname = request.getParameter("dst_fname");
//To get whole source file name
src_fname=this.getServletContext().getRealPath(src_fname);
src_fname = src_fname.replace('/',File.separatorChar);
try {
DownLoad.donwload(request, response, src_fname, dst_fname);
}
catch (DowLoadException ex) {
//throw new ServletException(ex);
ex.printStackTrace(System.out);
}
return;
}
//Clean up resources
public void destroy() {
}
}
package com.netec.util;
public class ConversionHtml {
/**
* (Constructor)
*
*/
private ConversionHtml() {
super();
}
public static String StringToHtml(String str) {
String repStr = str;
repStr = repStr.replaceAll("/r/n", "<BR>");
repStr = repStr.replaceAll("/r", "<BR>");
repStr = repStr.replaceAll("/n", "<BR>");
repStr = repStr.replaceAll(" ", " ");
return repStr;
}
public static String HtmlToString(String str) {
String repStr = str;
repStr = repStr.replaceAll("<br>|<BR>|<Br>|<bR>|<br/>|<BR/>", "/r/n");
repStr = repStr.replaceAll(" ", " ");
return repStr;
}
}
package com.netec.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class RequestNativeProxy implements HttpServletRequest {
private HttpServletRequest request;
public RequestNativeProxy(HttpServletRequest request) {
super();
this.request=request;
}
public String getAuthType() {
return request.getAuthType();
}
public Cookie[] getCookies() {
return request.getCookies();
}
public long getDateHeader(String arg0) {
return request.getDateHeader(arg0);
}
public String getHeader(String arg0) {
return request.getHeader(arg0);
}
public Enumeration getHeaders(String arg0) {
return request.getHeaders(arg0);
}
public Enumeration getHeaderNames() {
return request.getHeaderNames();
}
public int getIntHeader(String arg0) {
return request.getIntHeader(arg0);
}
public String getMethod() {
return request.getMethod();
}
public String getPathInfo() {
return request.getPathInfo();
}
public String getPathTranslated() {
return request.getPathTranslated();
}
public String getContextPath() {
return request.getContextPath();
}
public String getQueryString() {
return request.getQueryString();
}
public String getRemoteUser() {
return request.getRemoteUser();
}
public boolean isUserInRole(String arg0) {
return request.isUserInRole(arg0);
}
public Principal getUserPrincipal() {
return request.getUserPrincipal();
}
public String getRequestedSessionId() {
return request.getRequestedSessionId();
}
public String getRequestURI() {
return request.getRequestURI();
}
public StringBuffer getRequestURL() {
return request.getRequestURL();
}
public String getServletPath() {
return request.getServletPath();
}
public HttpSession getSession(boolean arg0) {
return request.getSession(arg0);
}
public HttpSession getSession() {
return request.getSession();
}
public boolean isRequestedSessionIdValid() {
return request.isRequestedSessionIdValid();
}
public boolean isRequestedSessionIdFromCookie() {
return request.isRequestedSessionIdFromCookie();
}
public boolean isRequestedSessionIdFromURL() {
return request.isRequestedSessionIdFromURL();
}
public boolean isRequestedSessionIdFromUrl() {
throw new UnsupportedOperationException();
}
public Object getAttribute(String arg0) {
return request.getAttribute(arg0);
}
public Enumeration getAttributeNames() {
return request.getAttributeNames();
}
public String getCharacterEncoding() {
return request.getCharacterEncoding();
}
public void setCharacterEncoding(String arg0)
throws UnsupportedEncodingException {
request.setCharacterEncoding(arg0);
}
public int getContentLength() {
return request.getContentLength();
}
public String getContentType() {
return request.getContentType();
}
public ServletInputStream getInputStream() throws IOException {
return request.getInputStream();
}
public String getParameter(String arg0) {
try {
if(request.getParameter(arg0)!=null) {
return new String(request.getParameter(arg0).getBytes("ISO-8859-1"));
}else {
return null;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "null"+e.getMessage();
}
}
public Enumeration getParameterNames() {
return request.getParameterNames();
}
public String[] getParameterValues(String arg0) {
String[] values= request.getParameterValues(arg0);
for(int i=0;i<values.length;i++) {
try {
if(values[i]!=null) {
values[i]=new String(values[i].getBytes("ISO-8859-1"));
}else {
values[i]=null;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
values[i]="null"+e.getMessage();
}
}
return values;
}
public Map getParameterMap() {
String newValue;
String oldValue;
String name;
Enumeration names=request.getParameterNames();
Map parameterMap=request.getParameterMap();
while(names.hasMoreElements()) {
name=(String)names.nextElement();
oldValue=(String)parameterMap.get(name);
try {
if(oldValue!=null) {
newValue=new String(oldValue.getBytes("ISO-8859-1"));
}else {
newValue=null;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
newValue="null"+e.getMessage();
}
parameterMap.put(name,newValue);
}
return parameterMap;
}
public String getProtocol() {
return request.getProtocol();
}
public String getScheme() {
return request.getScheme();
}
public String getServerName() {
return request.getServerName();
}
public int getServerPort() {
return request.getServerPort();
}
public BufferedReader getReader() throws IOException {
return request.getReader();
}
public String getRemoteAddr() {
return request.getRemoteAddr();
}
public String getRemoteHost() {
return request.getRemoteHost();
}
public void setAttribute(String arg0, Object arg1) {
request.setAttribute(arg0,arg1);
}
public void removeAttribute(String arg0) {
request.removeAttribute(arg0);
}
public Locale getLocale() {
return request.getLocale();
}
public Enumeration getLocales() {
return request.getLocales();
}
public boolean isSecure() {
return request.isSecure();
}
public RequestDispatcher getRequestDispatcher(String arg0) {
return request.getRequestDispatcher(arg0);
}
public String getRealPath(String arg0) {
throw new UnsupportedOperationException();
}
public int getRemotePort() {
throw new UnsupportedOperationException();
}
public String getLocalName() {
throw new UnsupportedOperationException();
}
public String getLocalAddr() {
throw new UnsupportedOperationException();
}
public int getLocalPort() {
throw new UnsupportedOperationException();
}
}
web.xml 中加如下
<servlet>
<servlet-name>download</servlet-name>
<servlet-class>
com.netec.util.download.servlet.DownLoadServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>download</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
jsp页面如下
<a href="/download?src_fname=XXX.jsp&dst_fname=下载后保存的文件名" />下载</a>
相关文章推荐
- PHP实现点击a标签的href做链接时,直接保存文件(任何类型),而不是通过浏览器直接打开下载的文件
- php -- PHP实现点击a标签的href做链接时,直接保存文件(任何类型),而不是通过浏览器直接打开下载的文件
- JavaWeb文件下载,提示用户保存而不是让浏览器直接打开
- 文件下载 浏览器直接打开文件而不是保存 相关问题
- 设置ngnix下的文件在浏览器端直接下载而不是被浏览器默认打开
- 在iis中设置文件下载而不是在浏览器上打开
- .net C# 实现点击下载PDF文件(通知浏览器打开下载对话框) 不是直接打开
- 记录一下:上传到服务器上的pdf 文件直接下载而非在浏览器里打开
- 在java的WEB项目如何防止浏览器直接打开下载的文件
- 在ASP.NET中下载Text文件,而不是在浏览器中打开它
- 使用Servlet实现文件下载的时候,避免浏览器自动打开文件
- ASP.NET直接下载一个文件,而不是在IE中打开它
- jsp中让IE提示文件下载,而不是直接打开
- [问题]如何直接在网页中打开文件 不出现下载保存提示框!
- 下载文件的jsp(不是直接打开)
- 防浏览器直接打开文件的java下载
- 默认点击下载pdf等文件而不是在浏览器中打开
- 轻松下载.pdf文件(直接下载,而不是在IE浏览器里面打开)
- asp.net生成csv文件,并在客户端点击下载(文件流直接输出到客户端而不是先生成保存在服务端再下载)
- 解决Tomcat服务器下载 xls、rar等文件时浏览器直接打开而没弹出另存为对话框