文件下载

作者: wswenyue | 来源:发表于2014-10-03 20:42 被阅读97次

    文件名非中文下载设置

    private void download1(HttpServletResponse response)
                throws FileNotFoundException, IOException {
            String realpath = this.getServletContext().getRealPath("/download/1.jpg");
            String filename = realpath.substring(realpath.lastIndexOf("\\")+1);
            
            response.setHeader("Content-disposition", "attachment;filename=" + filename);
            
            FileInputStream in = new FileInputStream(realpath);
            int len = 0;
            byte buffer[] = new byte[1024];
            OutputStream out = response.getOutputStream();
            while ((len = in.read(buffer))>0){
                out.write(buffer, 0, len);
            }
            
            in.close();
        }
    

    文件为中文的下载设置

    //中文文件下载,需要用URL编码
        private void download2(HttpServletResponse response)
                throws FileNotFoundException, IOException {
            String realpath = this.getServletContext().getRealPath("/download/图片.jpg");
            String filename = realpath.substring(realpath.lastIndexOf("\\")+1);
            
            //URLEncoding URL编码
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename,"UTF-8"));
            
            FileInputStream in = new FileInputStream(realpath);
            int len = 0;
            byte buffer[] = new byte[1024];
            OutputStream out = response.getOutputStream();
            while ((len = in.read(buffer))>0){
                out.write(buffer, 0, len);
            }
            
            in.close();
        }
    

    相关文章

      网友评论

        本文标题:文件下载

        本文链接:https://www.haomeiwen.com/subject/zmoutttx.html