通過位元組流方式實現檔案下載以及其中的編碼問題
阿新 • • 發佈:2019-01-05
關鍵程式碼
- 頁面程式碼
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<title>Insert title here</title>
</head>
<body>
<!-- 每一個Servlet檔案或者是jsp檔案都是一個Servlet -->
<a href="first?path=<%=getServletContext().getRealPath("文字.txt")%>">下載檔案</a>
</body>
</html>
- Servlet程式碼(採用的是靜態配置,在web.xml檔案中,在此省略)
package muchServlets;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public FirstServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path=request.getParameter("path");
System.out.println("path1:"+path);//path1輸出的路徑中文亂碼
path=new String(path.getBytes("iso-8859-1"),"utf-8");
System.out.println("path2"+path);//path2輸出的路徑沒有亂碼問題
File file=new File(path);
InputStream is=new FileInputStream(file);
OutputStream os=response.getOutputStream();
//設定響應頭
//這裡的檔名前面的編碼格式為什麼採用gbk 或者gb2312不是很清楚
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(file.getName().getBytes("gb2312"),"ISO-8859-1"));
response.addHeader("Content-Length", file.length() + "");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/plain");
//response響應頭的正文部分
//因為採用的是位元組流進行響應,所以文字的內容無須解決編碼的問題
//工程的程式碼編碼格式為工程下的設定
int data=0;
while((data=is.read())!=-1)
{
os.write(data);
}
os.close();
is.close();
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}