把response body以流的形式下载文件

 @GetMapping("downProcessFile.do")
    @ApiOperation(value = "test导出", tags = {"productAccess"}, httpMethod = "GET")
    public void downProcessFile(HttpServletRequest request, HttpServletResponse response) {
        String url = "http://fsmartbucket-30011.sz.gfp.tencent-cloud.com/123aa21088d846d8931cb463defd6694xlsx";
        String url2="http://fsmartbucket-30011.sz.gfp.tencent-cloud.com/123aa21088d846d8931cb463defd6694xlsx";
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url2);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int ret = httpResponse.getStatusLine().getStatusCode();
            long contentLength = httpResponse.getEntity().getContentLength();
            InputStream fis = httpResponse.getEntity().getContent();
           *//* BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuffer sb = new StringBuffer();*//*

            // File file = new File(path);
//            String filename = file.getName();// 获取日志文件名称
            String filename = "abc.xlsx";
//            fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
// 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.replaceAll(" ", "").getBytes("utf-8"), "iso8859-1"));
            response.addHeader("Content-Length", "" + contentLength);
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            //response.setContentType("application/octet-stream");
            response.setContentType("application/vnd.ms-excel");
            os.write(buffer);// 输出文件
            os.flush();
            os.close();
        } catch (Exception e) {
            e.getMessage();
        }
    }
    @GetMapping("downProcessFile2.do")
    @ApiOperation(value = "test导出2", tags = {"productAccess"}, httpMethod = "GET")
    public void downProcessFile2() throws Exception{

        String getURL="http://fsmartbucket-30011.sz.gfp.tencent-cloud.com/123aa21088d846d8931cb463defd6694xlsx";

        URL getUrl = new URL(getURL);

        // 根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型,
        // 返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection
        HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
        // 进行连接,但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到
        // 服务器
        connection.setConnectTimeout(25000);
        connection.setReadTimeout(25000);
        connection.connect();

        int status = connection.getResponseCode();
        if (status == 200) {
            DataInputStream in = new DataInputStream( connection.getInputStream());
            DataOutputStream out = new DataOutputStream(new FileOutputStream("abc.xlsx"));
            byte[] buffer = new byte[4096];
            int count = 0;
            while ((count = in.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
            out.close();
            in.close();
        } else {
            String strResponse = "error";
        }
        connection.disconnect();

    }


    /**
     * 产品手册批量下载(以压缩包的格式)
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("downloadManual")
    public HttpServletResponse downLoadFiles(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            File dir = new File("E:\\manual\\");
            *//**创建一个临时压缩文件,我们会把文件流全部注入到这个文件中,这里的文件你可以自定义是.rar还是.zip**//*
            File file = new File("E:/manual.rar");
            if (!file.exists()) {
                file.createNewFile();
            }
            response.reset();
            return downloadZip(file, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        *//**直到文件的打包已经成功了,文件的打包过程被我封装在FileUtil.zipFile这个静态方法中,稍后会呈现出来,接下来的就是往客户端写数据了**//*
        return response;
    }

    /**
     * 以流的形式下载文件
     *
     * @param file
     * @param response
     * @return
     */
    public static HttpServletResponse downloadZip(File file, HttpServletResponse response) {
        try {
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            //如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                File f = new File(file.getPath());
//                f.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return response;
    }

    /**
     * 根据输入的文件与输出流对文件进行打包
     *
     * @param inputFile
     * @param ouputStream
     */
    public static void zipFile(File inputFile, ZipOutputStream ouputStream) {
        try {
            if (inputFile.exists()) {
                *//**如果是目录的话这里是不采取操作的,至于目录的打包正在研究中**//*
                if (inputFile.isFile()) {
                    FileInputStream IN = new FileInputStream(inputFile);
                    BufferedInputStream bins = new BufferedInputStream(IN, 1024);
                    //org.apache.tools.zip.ZipEntry
                    ZipEntry entry = new ZipEntry(inputFile.getName());
                    ouputStream.putNextEntry(entry);
                    // 向压缩文件中输出数据
                    int nNumber;
                    byte[] buffer = new byte[1024];
                    while ((nNumber = bins.read(buffer)) != -1) {
                        ouputStream.write(buffer, 0, nNumber);
                    }
                    // 关闭创建的流对象
                    bins.close();
                    IN.close();
                } else {
                    try {
                        File[] files = inputFile.listFiles();
                        for (int i = 0; i < files.length; i++) {
                            zipFile(files[i], ouputStream);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @GetMapping("downProcessFile3.do")
    @ApiOperation(value = "test导出3", tags = {"productAccess"}, httpMethod = "GET")
    public Response<JSONObject> downProcessFile3(String url, String name, HttpServletResponse response) {
        String url2="http://fsmartbucket-30011.sz.gfp.tencent-cloud.com/123aa21088d846d8931cb463defd6694xlsx";
        HttpURLConnection conn = null;
        try {
            URL path = new URL(url2);
            conn = (HttpURLConnection) path.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream fis = conn.getInputStream();// 通过输入流获取数据

            byte[] buffer = readInputStream(fis);
            if (null != buffer && buffer.length > 0) {
                // 清空response
                response.reset();
                // 设置response的Header
                response.addHeader("Content-Disposition","attachment;filename="+ new String(("abc.xlsx").getBytes("GBK"),"ISO8859_1"));
                response.addHeader("Content-Length", "" + buffer.length);
                OutputStream toClient = response.getOutputStream();
                response.setContentType("application/octet-stream");
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            }

        } catch (IOException ex) {
            ex.printStackTrace();
        }finally {
            if(conn != null) {
                conn.disconnect();
            }
        }
    }


    /**
     * 从输入流中获取数据
     * @param fis 输入流
     * @return
     * @throws IOException
     */
    private byte[] readInputStream(InputStream fis) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=fis.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        fis.close();
        return outStream.toByteArray();
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值