![](/img/trans.png)
[英]Receive file stream through REST web service ResponseEntity<byte[]>
[英]How can we export json as a file through a rest web service?
我通过现有的rest服务将对象作为json返回,但是我希望将json保存到用户本地磁盘。
您可以在服务器中写入文件。 并使用以下代码将文件发送给用户。
String path = context.getSession().getServletContext().getRealPath("/") + "path to file";
InputStream inputStream = prepairFileStream(response, path);
if (inputStream == null) return;
FileCopyUtils.copy(inputStream, response.getOutputStream());
只有用户可以选择将文件保存在其本地磁盘上。
您可以建议浏览器(假设用户使用了浏览器)通过在响应中包含Content-Disposition
标头来提示用户“另存为...”对话框:
Content-Disposition: attachment; filename="fname.json"
( HTTP标头字段列表 )
您可以执行以下操作:
testFunction: function(req, res){
var yourJson = {"test":"testing"};
var text={"filename.txt":yourJson};
res.set({'Content-Disposition': 'attachment;filename=\"cards.txt\"','Content-type': 'text/plain'});
res.send(text['filename.txt']);
}
这会将您的json数据作为文件下载到您的下载文件夹中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.