title: AmazonS3 putObject with InputStream length example
body: <p>I am uploading a file to S3 using Java - this is what I got so far:</p>
  
  <pre><code>AmazonS3 s3 = new AmazonS3Client(new BasicAWSCredentials("XX","YY"));
  
  List&lt;Bucket&gt; buckets = s3.listBuckets();
  
  s3.putObject(new PutObjectRequest(buckets.get(0).getName(), fileName, stream, new ObjectMetadata()));
  </code></pre>
  
  <p>The file is being uploaded but a WARNING is raised when I am not setting the content length:</p>
  
  <blockquote>
  <pre><code>com.amazonaws.services.s3.AmazonS3Client putObject: No content length specified for stream &gt; data.  Stream contents will be buffered in memory and could result in out of memory errors.
  </code></pre>
  </blockquote>
  
  <p>This is a file I am uploading and the <code>stream</code> variable is an <code>InputStream</code>, from which I can get the byte array like this: <code>IOUtils.toByteArray(stream)</code>.</p>
  
  <p>So when I try to set the content length and MD5 (taken from <a href="https://stackoverflow.com/questions/415953/generate-md5-hash-in-java">here</a>) like this:</p>
  
  <pre><code>// get MD5 base64 hash
  MessageDigest messageDigest = MessageDigest.getInstance("MD5");
  messageDigest.reset();
  messageDigest.update(IOUtils.toByteArray(stream));
  byte[] resultByte = messageDigest.digest();
  String hashtext = new String(Hex.encodeHex(resultByte));
  
  ObjectMetadata meta = new ObjectMetadata();
  meta.setContentLength(IOUtils.toByteArray(stream).length);
  meta.setContentMD5(hashtext);
  </code></pre>
  
  <p><strong>It causes the following error to come back from S3:</strong></p>
  
  <blockquote>
    <p>The Content-MD5 you specified was invalid.</p>
  </blockquote>
  
  <p>What am I doing wrong?</p>
  
  <p>Any help appreciated!</p>
  
  <p><strong>P.S.</strong> I am on Google App Engine - I cannot write the file to disk or <a href="http://www.java2s.com/Code/JavaAPI/java.io/FilecreateTempFileStringprefixStringsuffix.htm" rel="noreferrer">create a temp file</a> because AppEngine does not support FileOutputStream.</p>