有关于文件下载接口的问题

Opticalproperti 2020-01-15 01:23:04
现在服务器上有个压缩文件,在liunx系统 usr/local/file 文件夹下面
我怎么写一个接口,访问接口直接下载这个文件呢?
...全文
231 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
Opticalproperti 2020-01-16
  • 打赏
  • 举报
回复
 @GetMapping("/download")
    @ResponseBody
    public ResponseEntity<byte[]> download() throws IOException {
        File file=new File("文件的绝对路径");
        HttpHeaders headers = new HttpHeaders();
        String fileName=new String(("文件名"+".tar").getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题
        headers.setContentDispositionFormData("attachment", fileName); //下载后显示的名字
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);  //向浏览器发送数据
    }
本来是这个问题,已经写出来了
Mister_X 2020-01-15
  • 打赏
  • 举报
回复
public static boolean httpDownload(String httpUrl, String saveFile) { // 1.下载网络文件 int byteRead; URL url; try { url = new URL(httpUrl); } catch (MalformedURLException e1) { e1.printStackTrace(); return false; } try { //2.获取链接 URLConnection conn = url.openConnection(); //3.输入流 InputStream inStream = conn.getInputStream(); //3.写入文件 FileOutputStream fs = new FileOutputStream(saveFile); byte[] buffer = new byte[1024]; while ((byteRead = inStream.read(buffer)) != -1) { fs.write(buffer, 0, byteRead); } inStream.close(); fs.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } }
Opticalproperti 2020-01-15
  • 打赏
  • 举报
回复
有大佬交流一下吗?

81,092

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧