首页 > 代码库 > 01 文件下载编码问题

01 文件下载编码问题

    /**     * 文件下载     *      * @param id     * @param basePath     * @param response     * @throws Exception     */        @RequestMapping(value = "/file_download", method = { RequestMethod.POST,RequestMethod.GET })    public void downloadCommon(String id, HttpServletRequest request, HttpServletResponse response)            throws Exception {                //调用ServletOutputStream或者Writer之前有效。        //当使用的缓存已满时,容器必须立刻刷新把缓存的内容发送到客户端,如果这是第一个被发送到客户端的数据,那么response也会被认为是已提交        response.reset();        response.setHeader("Content-Type", "application/force-download");                String encode = request.getParameter("encode");        if (encode != null && !"".equals(encode)) {            try {                request.setCharacterEncoding(ENCODING);            } catch (UnsupportedEncodingException e) {                request.setCharacterEncoding(ENCODING);            }        } else {            request.setCharacterEncoding(ENCODING);        }                String path = null;        String fileName=null;        String saveFileName=null;                InputStream input =null;        OutputStream output = null;                try {                        // 构建流            input = new FileInputStream(path + File.separator + fileName);            output =response.getOutputStream();      
if(request.getHeader("user-agent").indexOf("MSIE") != -1 || request.getHeader("user-agent").indexOf("like Gecko")!=-1) { saveFileName = java.net.URLEncoder.encode(saveFileName,ENCODING); } else { saveFileName = new String(saveFileName.getBytes(ENCODING),"iso-8859-1"); } //在response被提交前,头信息必须被设置,否则无效 //Content-Disposition 设置文件名,文件名有空格时下载文件名错误的解决办法 \fileName\ response.setHeader("Content-disposition", "inline;filename=\"" +saveFileName+"\""); // 输出文件流 byte[] buffer = new byte[1024]; int i = 0; while ((i = input.read(buffer)) != -1) { output.write(buffer, 0, i); } } catch (Exception e) { //TODO } finally { try { if(null !=output) { output.flush(); output.close(); } if(null !=input) { input.close(); } } catch (Exception e) { } } }

 

01 文件下载编码问题