以前我也遇到过这种问题, 主要是要用到toUtf8String()对中文进行转换. jsp文件: <a href="../share/downFiles.jsp?filename=<%=fjmc%>&path=AtthFiles/uploadXML" title='打开或下载相关链结文件'><img style="cursor:hand;border:0" alt="申请表" src="../images/document.gif"/><%=fjmc%></a>downFies.jsp实现: <%@ include file="../share/setup.jsp" %> <%@ page import = "com.guomao.util.*"%> <%! 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()); } } } return sb.toString(); } %> <% // 得到文件名字和路径 String filename = CTools.dbToWeb(request.getParameter("filename")); String path=CTools.dbToWeb(CTools.transfer(request.getParameter("path"))); String filepath ="../" + BASEDIR + path+"/"; // 设置响应头和下载保存的文件名 String CONTENT_TYPE = "text/html; charset=GBK"; response.setContentType(CONTENT_TYPE); response.setContentType("APPLICATION/OCTET-STREAM"); //System.out.println(filename+filepath); response.setHeader("Content-Disposition","attachment; filename=\"" + toUtf8String(filename) + "\""); // 打开指定文件的流信息 java.io.FileInputStream fileInputStream = new java.io.FileInputStream( filepath + filename); // 写出流信息 int i; while ((i=fileInputStream.read()) != -1) { response.getOutputStream().write(i); } fileInputStream.close(); response.getOutputStream().close(); %>
把中文文件名放到数据库中,然后在下载保存的时候给它重新起成中文文件名,其实文件在服务器上还是以英文保存。我以以回过关与下载 jpg 或基它文件自动打开的问题,其中有几个类,你可以直接拿过来用。 共五个类,分别如下,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; 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(); }}
to jianghuxing: 我试了你的方法,但是提示错误说 HTTP Status 404 - /download--------------------------------------------------------------------------------type Status reportmessage /downloaddescription The requested resource (/download) is not available. --------------------------------------------------------------------------------Apache Tomcat/5.0.28 我已经配置过web.xml的servlet了什么原因?望指教 谢谢
to jianghuxing :终于搞定了,太谢谢你了!!上面的问题也解决了,我把servlet mapping url-pattern 改了一个,就OK了另外,你给的代码里面把utf8编码转换注释掉了,我把他uncomment了才能变成中文的 anyway,thank you very much . 分不够的话可以再向我要:)还得感谢Goal3(拼命三郎) ,你的方法也行的
jsp文件:
<a href="../share/downFiles.jsp?filename=<%=fjmc%>&path=AtthFiles/uploadXML" title='打开或下载相关链结文件'><img style="cursor:hand;border:0" alt="申请表" src="../images/document.gif"/><%=fjmc%></a>downFies.jsp实现:
<%@ include file="../share/setup.jsp" %>
<%@ page import = "com.guomao.util.*"%>
<%!
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());
}
}
}
return sb.toString();
}
%>
<% // 得到文件名字和路径
String filename = CTools.dbToWeb(request.getParameter("filename"));
String path=CTools.dbToWeb(CTools.transfer(request.getParameter("path")));
String filepath ="../" + BASEDIR + path+"/";
// 设置响应头和下载保存的文件名
String CONTENT_TYPE = "text/html; charset=GBK";
response.setContentType(CONTENT_TYPE);
response.setContentType("APPLICATION/OCTET-STREAM");
//System.out.println(filename+filepath);
response.setHeader("Content-Disposition","attachment; filename=\"" + toUtf8String(filename) + "\""); // 打开指定文件的流信息
java.io.FileInputStream fileInputStream =
new java.io.FileInputStream( filepath + filename); // 写出流信息
int i;
while ((i=fileInputStream.read()) != -1) {
response.getOutputStream().write(i);
}
fileInputStream.close();
response.getOutputStream().close();
%>
共五个类,分别如下,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() {
}
}
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();
}}
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;
}
}
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>
我试了你的方法,但是提示错误说
HTTP Status 404 - /download--------------------------------------------------------------------------------type Status reportmessage /downloaddescription The requested resource (/download) is not available.
--------------------------------------------------------------------------------Apache Tomcat/5.0.28
我已经配置过web.xml的servlet了什么原因?望指教
谢谢
anyway,thank you very much . 分不够的话可以再向我要:)还得感谢Goal3(拼命三郎) ,你的方法也行的