Spring MVC提供http接口供下载文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013310119/article/details/82383946

网上收集资料整理了一些方法,实现文件下载:

方法一:

@Controller
public class DownLoadController {
    @RequestMapping(value="/zyg/download/lemmainfo")//请求路径
    public void downloadResource(@RequestParam(value = "fileName", required = true) String fileName, HttpServletResponse response) {
        String dataDirectory = "/data/denglinjie/everydayLemmaInfo/";//文件所在目录
        Path file = Paths.get(dataDirectory, fileName);//文件对象
        if (Files.exists(file)) {
            response.setContentType("application/x-gzip");
            try {
                response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            
            Files.copy(file, response.getOutputStream());//以输出流的形式对外输出提供下载
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

方法二:

 public HttpServletResponse download(String path, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }

可以参考:http://www.cnblogs.com/ungshow/archive/2009/01/12/1374491.html

猜你喜欢

转载自blog.csdn.net/u013310119/article/details/82383946