栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从Spring @Controller返回具有OutputStream的文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从Spring @Controller返回具有OutputStream的文件

您可以使用

ByteArrayOutputStream
ByteArrayInputStream
。例:

// A ByteArrayOutputStream holds the content in memoryByteArrayOutputStream outputStream = new ByteArrayOutputStream();// Do stuff with your OutputStream// To convert it to a byte[] - simply usefinal byte[] bytes = outputStream.toByteArray();// To convert bytes to an InputStream, use a ByteArrayInputStreamByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);

您可以 其他 流对 执行相同操作。例如文件流:

// Create a FileOutputStreamFileOutputStream fos = new FileOutputStream("filename.txt");// Write contents to file// Always close the stream, preferably in a try-with-resources blockfos.close();// The, convert the file contents to an input streamfinal InputStream fileInputStream = new FileInputStream("filename.txt");

而且,使用Spring MVC时,您绝对可以返回

byte[]
包含您的文件的。只要确保您使用注释您的回复即可
@ResponseBody
。像这样:

@ResponseBody@RequestMapping("/myurl/{filename:.*}")public byte[] serveFile(@PathVariable("file"} String file) throws IOException {    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();     DbxEntry.File downloadedFile = client.getFile("/" + filename, null, outputStream);    return outputStream.toByteArray();}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/430527.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号