java - 如何从 Google Cloud Storage 下载文件并在 Spring 控制器中返回
问题描述
我有一个 Spring Boot 应用程序。用户可以登录我的应用程序并上传文件。用户的所有文件都存储在 Google Cloud Storage 中。现在,我希望用户能够下载他们的文件。所以,我必须从云存储下载文件。我不知道我的控制器应该是什么样子。使用我当前的代码,我得到一个空文件。上传已经完成,连接也很好。
public static Blob downloadFile(Storage storage, String fileName){
Blob blob = storage.get(BUCKET_NAME, fileName);
return blob;
}
@RequestMapping(value = "/downloadFileTest")
@ResponseBody
public void downloadFile(HttpSession session,
HttpServletResponse response) {
Storage storage = de.msm.msmcenter.service.cloudstorage.Authentication.getStorage();
Blob blob = de.msm.msmcenter.service.cloudstorage.Authentication.downloadFile(storage,"test.txt");
ReadChannel readChannel = blob.reader();
InputStream inputStream = Channels.newInputStream(readChannel);
try {
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "attachment; filename=test.txt");
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
inputStream.close();
} catch (Exception e){
e.printStackTrace();
}
}
我实际上希望能够下载任何文件,而不仅仅是txt。当用户打开链接时,名称为 test.txt 的文件会被下载,但它是空的。
解决方案
您似乎只想授予用户下载文件的权限。
一个解决方案是使用Signed URL,它可以让您为用户提供 URL 以在有限的时间内访问/下载对象。如果您将用户直接重定向到该 URL,下载将立即开始。
推荐阅读
- git - 如何获取给定分支独有的提交列表
- arrays - RUBY 中的“参数数量错误”错误
- python-3.x - 如何从 html 中获取字典?
- mysql - IN MYSQL如何取每一行的最大计数?
- algorithm - 在完整的二分图中找到第二个最大加权匹配
- javascript - 有没有办法深度链接 Chrome 应用程序?
- ffmpeg - 如何将视频转换为使用 ffmpeg 同步的 gif 和 mp3?
- javascript - 我正在 reactJS 中使用 axios 进行 API 调用,但得到的结果比预期的要多
- php - 如何修复“laravel 邮件发送在本地主机上工作的实时服务器上不起作用”?
- javascript - Javascript 在 Internet Explorer 中不起作用,但在所有其他浏览器中不起作用。为什么?