欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springboot返回文件的两种方式

程序员文章站 2022-05-04 19:24:39
第一种,写入流里返回@RequestMapping(value = "/getVideo", method = RequestMethod.GET) public void getVido(HttpServletResponse response) { String file = "C:\\Users\\Boss\\Desktop\\123.avi"; try { FileInputStream inputStream = new FileI...

第一种,写入流里返回

@RequestMapping(value = "/getVideo", method = RequestMethod.GET)
    public void getVido(HttpServletResponse response) {
        String file = "C:\\Users\\Boss\\Desktop\\123.avi";
        try {
            FileInputStream inputStream = new FileInputStream(file);
            byte[] data = new byte[inputStream.available()];
            inputStream.read(data);
            String diskfilename = "final.avi";
            response.setContentType("video/avi");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + diskfilename + "\"");
            System.out.println("data.length " + data.length);
            response.setContentLength(data.length);
            response.setHeader("Content-Range", "" + Integer.valueOf(data.length - 1));
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Etag", "W/\"9767057-1323779115364\"");
            OutputStream os = response.getOutputStream();

            os.write(data);
            //先声明的流后关掉!
            os.flush();
            os.close();
            inputStream.close();

        } catch (Exception e) {
            e.printStackTrace();

        }
    }

第二种,用 @GetMapping注解 指定返回格式

 @GetMapping(value = "getMusic/{musicid}", produces = "audio/mp3")
    public byte[] getMusic(@PathVariable String musicid) {
        log.info("请求接口 /story/Book/getBook/ 参数:{}", JSON.toJSONString(musicid));
        MusicFile musicFile = null;
        try {
            musicFile = mongodbMapper.selectMusicByName(musicid);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return musicFile.getContent().getData();
    }

produces的类型可以在下面的网址查看:
https://tool.oschina.net/commons

本文地址:https://blog.csdn.net/qq_43578385/article/details/110168757

相关标签: SpringBoot