中文文件下载

2.中文文件下载:
假 如你的文件名是英文的话,jspsmartupload就可以胜任。但如果你的文件名是中文的话,就只能用下面的方法。这时jspsmartupload 是不能胜任的。以下例子能下载中文文件名(在firefox,ie8,360都通过测试, eclipse内置浏览器不行):
例 1.2.1
<%@ page contentType="text/html; charset=GBK" %>
<html>
<body >
<A href="http://localhost:8080/ServletHello/MarkToWinServlet?file=ibatis环境搭建.ppt">下 载ibatis环境搭建.ppt</A>
</body>
</html>



package com;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletHello1 extends HttpServlet {
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws IOException  {
        java.io.BufferedInputStream bis = null;
        java.io.BufferedOutputStream bos = null;
        try {
            String filenameiso = request.getParameter("file");
            System.out.println("filenameiso is " + filenameiso);
            String filenamegbk = new String(filenameiso.getBytes("iso8859-1"), "GBK");
            System.out.println("filenameutf is " + filenamegbk);
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-disposition", "attachment; filename="
                    + filenameiso);
            System.out.println("after setHeader");
            bis = new java.io.BufferedInputStream(new java.io.FileInputStream(
                    getServletContext().getRealPath("file/" + filenamegbk)));
            bos = new java.io.BufferedOutputStream(response.getOutputStream());
            System.out.println("after new bis bos ");
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            System.out.println("after while ");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }
        System.out.println("finish ");
    }
}


更多内容请见原文,文章转载自:https://blog.csdn.net/qq_44638460/article/details/104157358

posted @ 2022-03-23 16:26  malala  阅读(61)  评论(0编辑  收藏  举报