当前位置:首页 > 编程笔记 > 正文
已解决

从服务器指定位置下载文件

来自网友在路上 148848提问 提问时间:2023-09-22 07:12:33阅读次数: 48

最佳答案 问答题库488位专家为你答疑解惑

从服务器指定位置下载文件

  • 下载文件转换成流,这里说两种流的方式:
          • 1. 文件流
          • 2. 字节流

下载文件转换成流,这里说两种流的方式:

1. 文件流
2. 字节流

一,字节流

String filePath=“/opt/peoject/file/123/pdf”; //这个是你服务上存放文件位置

方法体,代码如下:

public byte[] downLoadFile(String filePath) throws Exception {byte[] buffer = null;try {File file = new File(filePath);FileInputStream fis = new FileInputStream(filePath);ByteArrayOutputStream bos = new ByteArrayOutputStream();byte[] b = new byte[1024];int n;while ((n = fis.read(b)) != -1) {bos.write(b, 0, n);}fis.close();bos.close();buffer = bos.toByteArray();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return buffer;}

后端 controller层:

@PostMapping("/downLoadFile")
public byte[] downLoadFile(HttpServletRequest request,HttpServletResponse response){return  downLoadFile2(response,filePath);
}

前端接收处理、

参考地址:文件下载

二,文件流

public void downLoadFile2(HttpServletResponse response,String filePath) throws Exception {File file = new File(filePath);//获取文件名称 (例如:123.pdf)String fileName=filePath.substring(filePath.lastIndexOf("\\"));InputStream inputStream = new FileInputStream(file);response.setContentType("application/pdf;charset=utf-8");response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");IOUtils.copy(inputStream, response.getOutputStream());response.flushBuffer();inputStream.close();}

后端controller

public void downLoadFile(HttpServletRequest request,HttpServletResponse response){downLoadFile2(response,filePath);
}

下载后,浏览器这里会有显示文件
在这里插入图片描述

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"从服务器指定位置下载文件":http://eshow365.cn/6-11278-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!