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();
}
标签:文件,通用,RequestParam,getOutputStream,inputStream,Java,fileName,response,下载 来源: https://blog.csdn.net/peach_garden/article/details/117985518