2

I'm trying to upload a file to Google Cloud Storage from my android app. I'm following the instructions here.

This is my code:

public static void uploadFileToServer(String localFilename) {

    HttpURLConnection conn = null;
    DataOutputStream dos = null;
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(localFilename);

    try {

            // Get the application specific upload URL
            HttpClient httpClient = new DefaultHttpClient();

            HttpGet httpGet = new HttpGet("http://<my-app-id>.appspot.com/createUploadUrl.php");
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity urlEntity = response.getEntity();
            InputStream in = urlEntity.getContent();
            String str = "";
            while (true) {
                int ch = in.read();
                if (ch == -1)
                    break;
                str += (char) ch;
            }

Up to here, everything seems ok. In "str" I get the url created by "CloudStorageTools::createUploadUrl()", something like http://.appspot.com/_ah/upload/AMmfu6Yqu4-6KDv4iqomFbHB5rP3SeDG4FYNVvtIX-FfZd0jtNU9PUHCxfzMLU75-81hNYQR_FIOp1xLnIDY-bj1X6r0pcSP0vBGy4-PZhXfSzzSjfsHpEohmVgZm29ULtqXIzcyN1DYxvgR3B8vLRu4Y-BN8Pgd5N16s00zJIVD0bUQXy_bvpA/ALBNUaYAAAAAVTjyDDQ250PQnVbkaLUZydeL9_gbbWs-/

Then, I try to upload (post) a file to that url (within the 10 minutes allowed):

            URL url = new URL(str);

            FileInputStream fileInputStream = new FileInputStream(sourceFile);

            // Open a HTTP  connection to  the URL
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true); // Allow Inputs
            conn.setDoOutput(true); // Allow Outputs
            conn.setUseCaches(false); // Don't use a Cached Copy
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("ENCTYPE", "multipart/form-data");
            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            conn.setRequestProperty("uploaded_file", "whatever.jpg");

            dos = new DataOutputStream(conn.getOutputStream());


            //Adding Parameter filename in server
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                            + "Thisfile.jpg" + "\"" + lineEnd);
            dos.writeBytes(lineEnd);

            // create a buffer of  maximum size
            bytesAvailable = fileInputStream.available();

            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {

                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            // Responses from the server (code and message)
            int serverResponseCode = conn.getResponseCode();

            //close the streams //
            fileInputStream.close();
            dos.flush();
            dos.close();


    } catch (Exception e) {
        e.printStackTrace();
    }
}

But the file is not uploaded.

This is the code in the "createUploadUrl.php":

<?php
    require_once 'google/appengine/api/cloud_storage/CloudStorageTools.php';
    use google\appengine\api\cloud_storage\CloudStorageTools;

    $options = [ 'gs_bucket_name' => 'my_bucket' ];  // Here using my bucket name
    $upload_url = CloudStorageTools::createUploadUrl('/UploadToServer.php', $options);

    echo $upload_url;
?>

And the code in "UploadToServer.php":

<?php
    move_uploaded_file($_FILES['uploaded_file']['tmp_name'], 'gs://<my_bucket>/new_file.jpg');
?>

The funny this is this code works with any other Apache server (without the createUploadUrl part), but not with Google Cloud Storage.

I think "$_FILES" may not be forwarded to "UploadToServer.php".

Any hints?

4
  • You may wish to use direct file upload if the files are expected to be smaller than 32MB. See stackoverflow.com/questions/29807050/…
    – Mars
    Apr 23, 2015 at 18:50
  • Have you tried settings a Content-Transfer-Encoding header? Also is UploadToServer.php triggered at all?
    – Mars
    Apr 23, 2015 at 19:03
  • OMG! So simple! Great @Mars!! that solved the problem, just modifying "runtime: php" by "runtime: php55" in "app.yaml". You know? I though direct file upload wasn't possible with Google Storage because of this note "Important: Direct file uploads to your POST handler, without using the App Engine upload service, are not supported and will fail." in cloud.google.com/appengine/docs/php/googlestorage/user_upload, but that may refer just to web applications. Thanks so much!
    – Achiles
    Apr 24, 2015 at 10:01
  • @Achiles please consider moving the solution to answer section and marking it as accepted to close this question off. Cheers, Apr 24, 2015 at 13:00

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.