Uploading image from Android to GCS

后端 未结 5 1381
生来不讨喜
生来不讨喜 2020-12-01 04:02

I am trying to upload an image from Android directly to Google cloud storage. But the API does not seem to work. They have some Java samples which are tied to the App engine

5条回答
  •  离开以前
    2020-12-01 04:23

    This snippet of code works for me great for uploading files from Android directly to GCS.

    File file = new File(Environment.getExternalStorageDirectory(), fileName);
    
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
    
            FileBody filebody = new FileBody(file,ContentType.create(mimeType), file.getName());
    
            MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();        
            multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            multipartEntity.addPart("file", filebody);
            httppost.setEntity(multipartEntity.build());
            System.out.println( "executing request " + httppost.getRequestLine( ) );
            try {
                HttpResponse response = httpclient.execute( httppost );
                Log.i("response", response.getStatusLine().toString());
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            httpclient.getConnectionManager( ).shutdown( );
    

    MultipartEntityBuilder class is not included into android standard libraries so you need to download httpclient and include into your project.

提交回复
热议问题