本帖最后由 hejinzhong 于 2014-9-12 21:31 编辑
- public class DownLoadServlet extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doPost(request, response);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
-
- String fileName = "Xxx";
-
- /*
- * 这里:是利用http协议为ISO-8859-1和计算机系统为GBK编码为基础
- */
- fileName = new String(fileName.getBytes("GBK"),"ISO-8859-1");
-
- //这个是提示浏览器进行下载操作
- response.setHeader("content-disposition","attachment;filename="+fileName);
-
- /*进行文件传输,这里将文件默认放在当前项目目录下
- * 根据下面源码可知,返回值为传递字节数
- */
-
- IOUtils.copy(this.getServletContext().getResourceAsStream(fileName),
- response.getOutputStream());
-
-
- /*
- 这里是直接将文件读取流中的内容写入服务器的反馈流中
-
- private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
- private static final int EOF = -1;
- public static int copy(InputStream input, OutputStream output)
- throws IOException {
- long count = copyLarge(input, output);
- if (count > Integer.MAX_VALUE) {
- return -1;
- }
- return (int) count;
- }
-
- public static long copyLarge(InputStream input, OutputStream output)
- throws IOException{
- return copyLarge(input, output, new byte[DEFAULT_BUFFER_SIZE]);
- }
-
- public static long copyLarge(InputStream input, OutputStream output, byte[] buffer)
- throws IOException {
- long count = 0;
- int n = 0;
- while (EOF != (n = input.read(buffer))) {
- output.write(buffer, 0, n);
- count += n;
- }
- return count;
- }
- */
- }
- }
复制代码
|
|