java servlet 下載文件

        resp.setContentType("text/html;charset=UTF-8");
        String path = "http://yjsy.cupl.edu.cn/attachments/article/2689/2017%E5%B9%B4%E7%A1%95%E5%A3%AB%E7%A0%94%E7%A9%B6%E7%94%9F%E7%BB%9F%E8%80%83%E6%8B%9F%E6%8B%9B%E7%94%9F%E8%AE%A1%E5%88%92.pdf";
        //設置返回頭
        resp.setHeader("Content-Disposition", "attachment;filename=" + filename);
        try {
            logger.debug("--- process start ---");
            URL url = new URL(path);
            // 返回一個 URLConnection 對象,它表示到 URL 所引用的遠程對象的鏈接。
            URLConnection uc = url.openConnection();
            //讀取文件
            InputStream in = uc.getInputStream();
            OutputStream out = resp.getOutputStream();
            //寫文件
            int b;
            while((b=in.read())!= -1)
            {
                out.write(b);
            }
            //流必定要記得關閉
            in.close();
            out.close();
        } catch (MalformedURLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
相關文章
相關標籤/搜索