moondaisy
moondaisy

Reputation: 4491

Upload blob in Azure using BlobOutputStream

I'm trying to upload a blob directly from a stream, since I don't know the length of the stream I decided to try with this answer.

This doesn't work, even though it reads from the stream and doesn't throw any exceptions the content isn't uploaded to my container.

I have no problem uploading from files, it only occurs when uploading from a stream.

This is my code, I added a few outs to check whether it was reading something or not but that wasn't the problem:

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 "";
}

It doesn't fails but it doesn't works.

Is there another way of doing this? Or am I missing something?

UPDATE: I've been checking and I think that the problem is with the InputStream itself, but I don't know why since the same stream will work just fine if I use it to upload to Amazon s3 for instance

Upvotes: 3

Views: 3266

Answers (1)

Peter Pan
Peter Pan

Reputation: 24138

I tried to reproduce your issue, but failed. According to your code, it seems that the only obvious missing thing is no calling blobOutputStream.flush(); before close the output stream via blobOutputStream.close();, but it works if missing flush method

Here is my testing code as below.

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

If you can update in more details, I think it's help for analysising the issue. Any concern, please feel free to let me know.

Upvotes: 2

Related Questions