无法从文件名中包含空格的 azure 下载和读取文件

问题描述

我正在尝试下载具有以下名称文件Some_name random 15 + 17.pdf。当我尝试从此文件中读取时,出现以下异常:

com.microsoft.azure.storage.StorageException: The specifed resource name contains invalid characters.
at com.microsoft.azure.storage.StorageException.translateFromHttpStatus(StorageException.java:175)
at com.microsoft.azure.storage.StorageException.translateException(StorageException.java:94)
at com.microsoft.azure.storage.core.StorageRequest.materializeException(StorageRequest.java:305)
at com.microsoft.azure.storage.core.ExecutionEngine.executeWithRetry(ExecutionEngine.java:175)
at com.microsoft.azure.storage.file.CloudFile.downloadAttributes(CloudFile.java:1492)
at com.microsoft.azure.storage.file.FileInputStream.<init>(FileInputStream.java:154)
at com.microsoft.azure.storage.file.CloudFile.openRead(CloudFile.java:1819)
at com.microsoft.azure.storage.file.CloudFile.openRead(CloudFile.java:1785)
at ch.prestige.tools.dossier.microservice.service.impl.AzureFileClientProvider.readFileContent(AzureFileClientProvider.java:166)

这是我用来下载文件代码

public AzureFile downloadFileFromFileShare(String fileName,String fileLocation) {
    getFile();
    final CloudFileClient fileClientReference = getFileClientReference();
    CloudFile cloudFile;
    try {
        final CloudFileShare fileShare = fileClientReference.getShareReference(fileLocation);
        cloudFile = fileShare.getRootDirectoryReference().getFileReference(fileName);
        log.info("Downloaded file: {} from azure file share",fileName);
        return new AzureFile(fileName,readFileContent(cloudFile));
    } catch (URISyntaxException | StorageException e) {
        log.error("Failed to retrieve file for document {}",fileName,e);
        throw new AzureFileStorageNotAvailableException("Failed to retrieve file");
    }
}

以及阅读内容

private ByteArrayResource readFileContent(CloudFile cloudFile) {
    try (final FileInputStream fileInputStream = cloudFile.openRead()) {
        final byte[] content = fileInputStream.readAllBytes();
        return new ByteArrayResource(content);
    } catch (StorageException e) {
        log.error("The specified file {} does not exist",cloudFile.getUri(),e);
        throw new AzureFileStorageNotAvailableException("The specified file " + cloudFile.getUri() + " does not exist");
    } catch (IOException e) {
        log.error("Failed to read file content of {}",e);
        throw new AzureFileStorageNotAvailableException("Failed to read file content of " + cloudFile.getUri());
    }
}

当我在 azure 库中调试时,我注意到正在将名称更改为:

https://Some_name%20random%2015%20+%2017.pdf 

有没有可能检索到具有这种名称文件。对于我上传的其他文件,下载似乎效果很好。

解决方法

请尽量使用最新版本的包,如:

    <dependency>
      <groupId>com.microsoft.azure</groupId>
      <artifactId>azure-storage</artifactId>
      <version>8.6.5</version>
    </dependency>

如果这仍然不能解决您的问题,请按照 official document 提供的命名约定来命名您的文件,这也可以用作规避问题的解决方案:

enter image description here