欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

word、PDF下载

程序员文章站 2022-04-09 09:24:18
...

    @RequestMapping("/getUpload")
    public void getUpload(HttpServletRequest request, HttpServletResponse response){
        String url = request.getParameter("url");
        url = "C:\\Users\\Administrator\\1560938151601.docx";
        File file=new File(url);
        String fileName=file.getName();
        String ext=fileName.substring(fileName.lastIndexOf(".")+1);
        String agent=(String)request.getHeader("USER-AGENT"); //判断浏览器类型
        try {
            if(agent!=null && agent.indexOf("Fireforx")!=-1) {
                fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");   //UTF-8编码,防止输出文件名乱码
            }
            else {
                fileName= URLEncoder.encode(fileName,"UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        BufferedInputStream bis=null;
        OutputStream os=null;
        response.reset();
        response.setCharacterEncoding("utf-8");
        if(ext=="docx") {
            response.setContentType("application/msword"); // word格式
        }else if(ext=="pdf") {
    		response.setContentType("application/pdf"); // pdf格式
    	}
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        try {
            bis=new BufferedInputStream(new FileInputStream(file));
            byte[] b=new byte[bis.available()+1000];
            int i=0;
            os = response.getOutputStream();   //直接下载导出
            while((i=bis.read(b))!=-1) {
                os.write(b, 0, i);
            }
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(os!=null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
相关标签: 下载