java.nio.file.NoSuchFileException - Загрузка файлов из GCS - PullRequest
0 голосов
/ 19 октября 2018

Я пытаюсь загрузить файл из Google Cloud Storage.Я использую код Google Github здесь, в строке 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 /аб / Desktop / File.rtf

1 Ответ

0 голосов
/ 17 декабря 2018

Код найден на GitHub в API Google .Часть и концепция, которые я пропустил:

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