Java教程

Java中实现文件下载通用方式

本文主要是介绍Java中实现文件下载通用方式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

文件下载只需要四步:

1.设置文件ContentType类型

response.setContentType("multipart/form-data");

2.设置文件头

response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

3.通过response获取ServletOutputStream对象(out)

InputStream inputStream = xxxxx.downloadFile(fileName);

4.写到输出流(out)中

IOUtils.copy(inputStream, response.getOutputStream());
inputStream.close();

下面给出代码块,亲测可执行:

1.基于OSS实现文件下载

    @RequestMapping(value = "/ossDown",method = RequestMethod.GET)
    @ResponseBody
    @SneakyThrows
    public void ossDown(@RequestParam("bucketName") String 
       bucketName,@RequestParam("fileName") String fileName, HttpServletResponse response){

        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;filename=" +URLEncoder.encode(fileName, "UTF-8"));
        InputStream inputStream = ossComponent.downloadFile(bucketName, fileName);
        IOUtils.copy(inputStream, response.getOutputStream());
        inputStream.close();
    }

  OSS执行组件部分,亲测可行,获取直达地址

2.基于minIO实现文件下载

/**
     * 下载文件
     * @param fileName
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/minioDown",method = RequestMethod.GET)
    @ResponseBody
    @SneakyThrows(Exception.class)
    public void minioDown(@RequestParam("fileName") String fileName, HttpServletResponse response)throws Exception {

        ObjectStat stat = minioUtils.statObject("peach", fileName);
        response.setContentType(stat.contentType());
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        InputStream in = minioUtils.getObject("", fileName);
        IOUtils.copy(in, response.getOutputStream());
        in.close();

    }

 

这篇关于Java中实现文件下载通用方式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!