下载文件

1.从网络中下载文件

    @Override
    @RequestMapping("/open/v1/file/downloadFile")
    public void downloadFile(String url, HttpServletResponse response) {
        if (url != null) {
            try {
                //对文件中文名进行转义处理
                String fileName = new File(url).getName();
                url = url.replace(fileName, URLEncoder.encode(fileName, "utf-8"));

                URL urls = new URL(url);
                URLConnection urlCon = urls.openConnection();
                InputStream in = urlCon.getInputStream();
                //设置响应类型
                response.setContentType("application/octet-stream");//应用程序强制下载
                response.setContentType("multipart/form-data");
                //设置响应头,对文件进行url编码
                String name = URLEncoder.encode(fileName, "UTF-8");
                response.setHeader("Content-Disposition", "attachment;filename=" + name);
                response.setContentLength(urlCon.getContentLength());
                OutputStream out = response.getOutputStream();
                byte[] b = new byte[1024];
                int len = 0;
                while ((len = in.read(b)) != -1) {
                    out.write(b, 0, len);
                }
                out.flush();
                out.close();
                in.close();
            } catch (IOException e) {
                logger.error(e.getMessage());
                throw new SunawException("文件下载异常");
            }
        }
    }

 

2.从本地中下载文件

    @Override
    @RequestMapping("/open/v1/file/downloadFile")
    public void downloadFile(String filePath, HttpServletResponse response) {

        try {
            //对文件中文名进行转义处理
            File file = new File(filePath);
            String fileName = file.getName();
            
            InputStream in = new FileInputStream(file);
            //设置响应类型
            response.setContentType("application/octet-stream");//应用程序强制下载
            response.setContentType("multipart/form-data");
            //设置响应头,对文件进行url编码
            String name = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            response.setContentLength(in.available()); //该代码可能有误,没测试过
            OutputStream out = response.getOutputStream();
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
            out.flush();
            out.close();
            in.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
            throw new SunawException("文件下载异常");
        }
    }

 

posted @ 2019-10-31 11:41  陌路×难飞  阅读(206)  评论(0编辑  收藏  举报