日期:2014-05-17  浏览次数:20710 次

我从网上搞了一个下载功能的代码,但我不理解其中的意思,麻烦各位大虾指教一下其中的意思
package com.xtsw.file.control;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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;

import com.xtsw.file.dao.Impl.DownLoadDao;
import com.xtsw.file.util.LogUtil;

public class DownLoadServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DownLoadDao td = new DownLoadDao();
OutputStream toClient = null;
InputStream fis = null;
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
int clicks = Integer.parseInt(request.getParameter("clicks"));
int file_id = Integer.parseInt(request.getParameter("file_id"));
String filename = request.getParameter("file_name");
String filefilename = td.getList(file_id, filename);
try {
//清除空白文档,不能进行关闭
response.reset();
// 设置response的Header,前面一个为名字,是不是默认名?,后面一个为值。
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(filename.getBytes(), "iso-8859-1"));
response.addHeader("Content-Type", "application/octet-stream"); // 以流的形式下载文件。 //下面这个是做什么的
fis = new BufferedInputStream(new FileInputStream(filefilename));
toClient = new BufferedOutputStream(response.getOutputStream());
copy(fis, toClient);//为什么要用这个方法?
toClient.flush();

td.update(clicks, file_id);
} catch (RuntimeException e) {
LogUtil.outLog(e.getMessage());
} finally {
if (fis != null) {
fis.close();
}
if (toClient != null) {
toClient.close();
}

}
}

public void copy(InputStream input, OutputStream output) {
byte[] buffer = new byte[1024 * 4];
int n = 0;
try {
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
} catch (IOException e) {
LogUtil.outLog(e.getMessage());
// System.out.println(e.getMessage());
}
}

}


------解决方案--------------------
中间两件话没了,补上:
response.setContentType("application/octet-stream;charset=GB2312"); response.setHeader("Content-Disposition","attachment; filename=\"" + FileName + "\"");