下载中文文件时,需要注意的地方就是中文文件名要使用URLEncoder.encode方法进行编码(URLEncoder.encode(fileName, "字符编码")),否则会出现文件名乱码。response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(fileName, "UTF-8"));
public void OutPutFile(HttpServletResponse response) throws IOException{
// 1.获取要下载的文件的绝对路径
String realPath=this.getServletContext().getRealPath("/download/1.jpg");
// 2.获取要下载的文件名
String realName=realPath.substring(realPath.lastIndexOf("\\")+1);
// 3.设置content-disposition响应头控制浏览器以下载的形式打开文件
response.setHeader("content-disposition", "attachment;filename="+realName);
// 4.获取要下载的文件输入流
InputStream in= new FileInputStream(realPath);
// 5.创建数据缓冲区
byte[] buffer=new byte[1024];
int len=0;
// 6.通过response对象获取OutputStream流
OutputStream outStream=response.getOutputStream();
// 7.将FileInputStream流写入到buffer缓冲区
while ((len=in.read(buffer))>0) {
outStream.write(buffer,0,len);
}
in.close();
// 8.使用OutputStream将缓冲区的数据输出到客户端浏览器
}
//输出文字
public void PrintWriterPractice(HttpServletResponse response) throws IOException{
response.setCharacterEncoding("UTF-8");
PrintWriter pWriter= response.getWriter();//输出流
response.setHeader("content-type", "text/html;charset=UTF-8");
String data="中国ren";
pWriter.println(data);
}
//输出数字
public void outOneNumber(HttpServletResponse resopnse) throws IOException{
resopnse.setHeader("content-type", "text/html;charset=UTF-8");
OutputStream outStream=resopnse.getOutputStream();
outStream.write("输出数字1:".getBytes("UTF-8"));
outStream.write((1+"").getBytes());
}
文件下载注意事项:编写文件下载功能时推荐使用OutputStream流,避免使用PrintWriter流,因为OutputStream流是字节流,可以处理任意类型的数据,而PrintWriter流是字符流,只能处理字符数据,如果用字符流处理字节数据,会导致数据丢失。
private void downloadFileByPrintWriter(HttpServletResponse response)
throws FileNotFoundException, IOException {
String realPath = this.getServletContext().getRealPath("/download/张家界国家森林公园.JPG");//获取要下载的文件的绝对路径
String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);//获取要下载的文件名
//设置content-disposition响应头控制浏览器以下载的形式打开文件,中文文件名要使用URLEncoder.encode方法进行编码
response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(fileName, "UTF-8"));
FileReader in = new FileReader(realPath);
int len = 0;
char[] buffer = new char[1024];
PrintWriter out = response.getWriter();
while ((len = in.read(buffer)) > 0) {
out.write(buffer,0,len);//将缓冲区的数据输出到客户端浏览器
}
in.close();
}
所以使用PrintWriter流处理字节数据,会导致数据丢失,这一点千万要注意,因此在编写下载文件功能时,要使用OutputStream流,避免使用PrintWriter流,因为OutputStream流是字节流,可以处理任意类型的数据,而PrintWriter流是字符流,只能处理字符数据,如果用字符流处理字节数据,会导致数据丢失。