java - java.nio.file.NoSuchFileException - 从 GCS 下载文件
问题描述
我正在尝试从 Google Cloud Storage 下载文件。我在第 1042 行使用 Google 的 Github 代码。我相信我的错误在于文件路径。路径变量用于说明文件下载到的位置及其新名称,对吗?请注意,我正在使用 JSP 按钮来启动该过程。为了让我自己更容易解决,我用字符串而不是 HttpServletRequest 替换了字符串和路径变量。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// [START storage_download_file]
// The name of the bucket to access
String bucketName = "media";
// The name of the remote file to download
String srcFilename = "File.rtf";
// The path to which the file should be downloaded
Path destFilePath = Paths.get("/Volumes/Macintosh HD/Users/ab/Desktop/File.rtf");
// Instantiate a Google Cloud Storage client
Storage storage = StorageOptions.getDefaultInstance().getService();
// Get specific file from specified bucket
Blob blob = storage.get(BlobId.of(bucketName, srcFilename));
// Download file to specified path
blob.downloadTo(destFilePath);
// [END storage_download_file]
}
引起:java.nio.file.NoSuchFileException:/Volumes/Macintosh HD/Users/ab/Desktop/File.rtf
解决方案
在GitHub 上的 Google API 中找到的代码。我缺少的部分和概念是
输出流 outStream = response.getOutputStream();
这会将数据发送回客户端的浏览器。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**** Define variables ****/
Storage storage = StorageOptions.getDefaultInstance().getService();
String bucketName = "bucketName";
String objectName = "objectName";
/**** Setting The Content Attributes For The Response Object ****/
String mimeType = "application/octet-stream";
response.setContentType(mimeType);
/**** Setting The Headers For The Response Object ****/
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", objectName);
response.setHeader(headerKey, headerValue);
/**** Get the Output Stream of the Response Object****/
OutputStream outStream = response.getOutputStream();
/**** Call download method ****/
run(storage, bucketName, objectName, outStream);
}
private void run(Storage storage, String bucketName, String objectName, OutputStream outStream)throws IOException {
/**** Getting the blob ****/
BlobId blobId = BlobId.of(bucketName, objectName);
Blob blob = storage.get(blobId);
/**** Writing the content that will be sent in the response ****/
byte[] content = blob.getContent();
outStream.write(content);
outStream.close();
}
推荐阅读
- python - 如何将我的 Python 应用程序移动到网络上?
- python - 在此 python 代码中查找静态、实例和局部变量
- java - ClassNotFoundException 尽管类存在并已加载
- python - 如何打开第二个窗口然后隐藏它?
- c# - Azure:SDK 生成的共享访问签名在浏览器中不起作用
- reactjs - 新文件上的导出类不起作用(反应原生)
- laravel - 在heroku上部署laravel失败
- javascript - 我正在尝试在应用程序中放置一个视频(mp4),但它没有播放
- npm - 我删除了 npm 但它仍然存在
- asp.net - HTML 助手操作链接