title: How to properly upload (image) file to Google Cloud Storage using Java App Engine?
body: <p>I have a Google app engine instance, using java (sdk 1.9.7), and it is connected to Google Cloud Storage. I'm able to successfully take a request's input and output it to a file/object in my google cloud storage bucket. here's my code for my servlet:</p>
  
  <pre><code>public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
      // read the input stream
      byte[] buffer = new byte[1024];
      List&lt;byte[]&gt; allBytes = new LinkedList&lt;byte[]&gt;();
      InputStream reader = req.getInputStream();
      while(true) {
          int bytesRead = reader.read(buffer);
          if (bytesRead == -1) {
              break; // have a break up with the loop.
          } else if (bytesRead &lt; 1024) {
              byte[] temp = Arrays.copyOf(buffer, bytesRead);
              allBytes.add(temp);
          } else {
              allBytes.add(buffer);
          }
      }
  
      // init the bucket access
      GcsService gcsService = GcsServiceFactory.createGcsService(RetryParams.getDefaultInstance());
      GcsFilename filename = new GcsFilename("my-bucket", "my-file");
      Builder fileOptionsBuilder = new GcsFileOptions.Builder();
      fileOptionsBuilder.mimeType("text/html"); // or "image/jpeg" for image files
      GcsFileOptions fileOptions = fileOptionsBuilder.build();
      GcsOutputChannel outputChannel = gcsService.createOrReplace(filename, fileOptions);
  
      // write file out
      BufferedOutputStream outStream = new BufferedOutputStream(Channels.newOutputStream(outputChannel));
      for (byte[] b : allBytes) {
          outStream.write(b);
      }
      outStream.close();
      outputChannel.close();
  }
  </code></pre>
  
  <p>and when i do something like a curl POST command, this works perfectly if i just feed it data directly, like so:</p>
  
  <pre><code>curl --data "someContentToBeRead" http://myAppEngineProj.appspot.com/myServlet
  </code></pre>
  
  <p>and i can see the exactly string that i put in, "someContentToBeRead".</p>
  
  <p>HOWEVER, when i put a file, like so:</p>
  
  <pre><code>curl -F file=@"picture.jpg" http://myAppEngineProj.appspot.com/myServlet
  </code></pre>
  
  <p>the file is completely corrupted. if i upload a text file, it has a line of crap in the beginning of the file, and a line of crap at the end, like:</p>
  
  <pre><code>------------------------------266cb0e18eba
  Content-Disposition: form-data; name="file"; filename="blah.txt"
  Content-Type: text/plain
  
  hi how are you
  
  ------------------------------266cb0e18eba--
  </code></pre>
  
  <p>how do i tell cloud storage i want to store the data as file?</p>