【问题标题】:Upload blob in Azure using BlobOutputStream使用 BlobOutputStream 在 Azure 中上传 Blob
【发布时间】:2017-04-06 12:46:43
【问题描述】:

我正在尝试直接从流上传 Blob,因为我不知道流的长度我决定尝试使用 this answer

这不起作用,即使它从流中读取并且没有抛出任何异常,内容也没有上传到我的容器中。

我从文件上传没有问题,只有从流上传时才会出现。

这是我的代码,我添加了一些输出来检查它是否正在读取某些内容,但这不是问题:

try {
    CloudBlockBlob blob = PublicContainer.getBlockBlobReference(externalFileName);
    if (externalFileName.endsWith(".tmp")) {
        blob.getProperties().setContentType("image/jpeg");
    }
    BlobOutputStream blobOutputStream = blob.openOutputStream();
    int next = input.read();
    while (next != -1) {
        System.err.println("writes");
        blobOutputStream.write(next);
        next = input.read();
    }
    blobOutputStream.close();
    return blob.getUri().toString();

} catch (Exception usex) {
    System.err.println("ERROR " + usex.getMessage());
    return "";
}

它没有失败,但它不起作用。

还有其他方法吗?还是我错过了什么?

更新:我一直在检查,我认为问题出在 InputStream 本身,但我不知道为什么,因为如果我用它来上传相同的流会正常工作以 Amazon s3 为例

【问题讨论】:

    标签: java azure azure-storage azure-blob-storage


    【解决方案1】:

    我试图重现您的问题,但失败了。根据您的代码,似乎唯一明显缺少的是在通过blobOutputStream.close(); 关闭输出流之前没有调用blobOutputStream.flush();,但如果缺少flush 方法,它会起作用

    这是我的测试代码如下。

    String STORAGE_CONNECTION_STRING_TEMPLATE = "DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s;";
    
    String accountName = "xxxx";
    String key = "XXXXXX";
    CloudStorageAccount account = CloudStorageAccount.parse(String.format(STORAGE_CONNECTION_STRING_TEMPLATE, accountName, key));
    CloudBlobClient client = account.createCloudBlobClient();
    CloudBlobContainer container = client.getContainerReference("mycontainer");
    container.createIfNotExists();
    String externalFileName = "test.tmp";
    CloudBlockBlob blob = container.getBlockBlobReference(externalFileName);
    if (externalFileName.endsWith(".tmp")) {
        blob.getProperties().setContentType("image/jpeg");
    }
    BlobOutputStream blobOutputStream = blob.openOutputStream();
    String fileName = "test.jpg";
    InputStream input = new FileInputStream(fileName);
    int next = -1;
    while((next = input.read()) != -1) {
        blobOutputStream.write(next);
    }
    blobOutputStream.close(); // missing in your code, but works if missing.
    input.close();
    

    如果您可以更详细地更新,我认为这有助于分析问题。有任何问题,请随时告诉我。

    【讨论】:

    • 谢谢,我会试着找出问题所在,因为它似乎自己工作得很好
    猜你喜欢
    • 1970-01-01
    • 2013-09-21
    • 2013-10-30
    • 2020-03-12
    • 2018-12-29
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    相关资源
    最近更新 更多