我在做jsp的下載功能時遇到了問題,不知道什麼原因:
首先我做了一個jsp檔案:filedown.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>你好</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<a href="DownloadServlet">download</a>
</body>
</html>
然後我做了一個servlet:DownloadServlet.java
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DownloadServlet extends HttpServlet {
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String filePath ="D:/apple/2007.doc";
String fileType ="doc";
File file = new File(filePath);
response.setCharacterEncoding("gb2312");
response.setContentType(fileType);
response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getName().getBytes("gb2312"),"iso8859-1"));
System.out.println(new String(file.getName().getBytes("gb2312"),"gb2312"));
OutputStream output = null;
FileInputStream fis = null;
try
{
output = response.getOutputStream();
fis = new FileInputStream(file);
byte[] b = new byte[1024];
int i = 0;
System.out.println("++++++++++++++++++++++++++++");
while((i = fis.read(b))!=-1)
{
output.write(b, 0, i);
}
output.write(b, 0, b.length);
System.out.println("++++++++++++++++++++++++++++");
output.flush();
response.flushBuffer();
}
catch(Exception e)
{
System.out.println("Error!");
e.printStackTrace();
}
finally
{
if(fis != null)
{
fis.close();
fis = null;
}
if(output != null)
{
output.close();
output = null;
}
}
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
上面的servlet是我在網上找到的原始碼,我加了output.write(b, 0, b.length);這句話。(可是我加沒加效果都一樣,都是錯的)
我的準備工作是:D:/apple/2007.doc這個檔案是肯定存在的。