java.nio.file.NoSuchFileException-从GCS下载文件

时间:2018-10-19 18:26:32

标签: java google-cloud-platform nosuchfileexception

我正在尝试从Google Cloud Storage下载文件。我正在使用Google的Github代码here on line 1042。我相信我的错误与文件路径有关。 path变量用于说明文件下载到的位置以及文件的新名称,对吗?注意,我正在使用JSP按钮来启动该过程。为了使自己更容易解决,我将String和Path变量替换为Strings而不是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

1 个答案:

答案 0 :(得分:0)

GitHub in the Google APIs上找到的代码。我缺少的部分和概念是

OutputStream 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();
}