답변

5

모바일 백엔드 스타터로 내 expirience 공유.

public String getUploadBlobURL(String bucketName, String path, String accessMode) { 

     String url = null; 
     try { 
      url = getMBSEndpoint().blobEndpoint() 
        .getUploadUrl(bucketName, path, accessMode).execute() 
        .getShortLivedUrl(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return url; 
    } 

public String getDownloadBlobURL(String bucketName, String path) { 

     String url = null; 
     try { 
      url = getMBSEndpoint().blobEndpoint() 
        .getDownloadUrl(bucketName, path).execute() 
        .getShortLivedUrl(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return url; 
    } 

그런 다음 당신이 돕는 Google 클라우드 스토리지에 바이트를 스트리밍 URL을 사용할 수 있습니다

당신이 활동에서 액세스 할 수있는 URL을 만들기 위해 CloudBackend.java 클래스에이 두 가지 방법을 추가 할 필요가 업로드 및 다운로드 URL을 얻으려면 표준 클라이언트 라이브러리

아래에서는 사용 방법에 대해 설명하겠습니다.

File fileUp = new File(Environment.getExternalStorageDirectory(), fileName); 
     new AsyncBlobUploader(this, mProcessingFragment.getCloudBackend()).execute(fileUp); 

AsyncTask를

public class AsyncBlobUploader extends AsyncTask<File, Void, String> { 
    private Context context; 
    private ProgressDialog pd; 
    private CloudBackend cb; 

    public AsyncBlobUploader(Context context, CloudBackend cb) { 
     this.context = context; 
     this.cb = cb; 
    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pd = ProgressDialog.show(context, null, 
       "Loading... Please wait..."); 
     pd.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
     pd.setIndeterminate(true); 
     pd.setCancelable(true); 
     pd.show(); 
    } 

    protected String doInBackground(File... files) { 
     File file = files[0]; 
     String uploadUrl = cb.getUploadBlobURL(bucketName, file.getName(),"PUBLIC_READ_FOR_APP_USERS"); 
     String url = uploadUrl.split("&Signature")[0]; // url without Signature 

     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(url); 

     FileBody filebody = new FileBody(file,ContentType.create(getMimeType(file 
       .toString())), 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(); 

     return (String) uploadUrl; 
    } 

    protected void onPostExecute(String result) { 

     pd.dismiss(); 
     Log.d("BlobUrl", result); 

    } 

    public static String getMimeType(String url) { 
     String type = null; 
     String extension = MimeTypeMap.getFileExtensionFromUrl(url); 
     if (extension != null) { 
      MimeTypeMap mime = MimeTypeMap.getSingleton(); 
      type = mime.getMimeTypeFromExtension(extension); 
     } 
     return type; 
    } 
} 

MultipartEntityBuilder 클래스에 포함되지 않습니다

활동 :이 비슷한을 사용할 수있다 Google 클라우드 스토리지에 파일을 업로드를 들어

안드로이드 표준 라이브러리 그래서 당신은 0을 다운로드해야합니다을 입력하고 프로젝트에 포함하십시오.

이 줄에주의하십시오. String url = uploadUrl.split("&Signature")[0]; 여기서 URL 서명을 자르고 있습니다. (URL 서명으로 나는 503 Internal Server Error 받고 있지만 오전없이 모든 작동 예상대로 나는 이런 일이 발생하지 왜..)

이 조각 사용할 수 있습니다 다운로드 :

활동

File fileDown = new File(Environment.getExternalStorageDirectory(), 
       fileName); //file to create 
     new AsyncBlobDownloader(imageView, mProcessingFragment.getCloudBackend()) 
      .execute(fileDown); 

AsyncTask를

public class AsyncBlobDownloader extends AsyncTask<File, Integer, File> { 
    private ImageView imageView; 
    private ProgressDialog pd; 
    private CloudBackend cb; 

    public AsyncBlobDownloader(ImageView imageView, CloudBackend cb) { 
     this.imageView = imageView; 
     this.cb = cb; 
    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     pd = ProgressDialog.show(imageView.getContext(), null, 
       "Loading... Please wait..."); 
     pd.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
     pd.setCancelable(true); 
     pd.show(); 
    } 

    protected File doInBackground(File... files) { 
     File file = files[0]; 
     String downloadUrl = cb.getDownloadBlobURL(bucketName, 
       file.getName()); 
     InputStream input = null; 
     OutputStream output = null; 
     HttpURLConnection connection = null; 
     try { 
      URL url = new URL(downloadUrl); 
      connection = (HttpURLConnection) url.openConnection(); 
      connection.connect(); 
      if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { 
       Log.i("Response", 
         "Server returned HTTP " + connection.getResponseCode() 
           + " " + connection.getResponseMessage()); 
      } 
      int fileLength = connection.getContentLength(); 

      input = connection.getInputStream(); 
      output = new FileOutputStream(file); 

      byte data[] = new byte[4096]; 

      int count; 
      while ((count = input.read(data)) != -1) { 
       if (isCancelled()) { 
        input.close(); 
        return null; 
       } 
       output.write(data, 0, count); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (output != null) 
        output.close(); 
       if (input != null) 
        input.close(); 
      } catch (IOException ignored) { 
      } 

      if (connection != null) 
       connection.disconnect(); 
     }  
     return file; 
    } 

    protected void onPostExecute(File result) {  
     pd.dismiss(); 
     imageView.setImageURI(Uri.fromFile(result)); 
    } 
} 

참고 : Google Cloud Storage를 사용하려면 결제를 사용해야합니다. 또한 GCS에서 버킷을 만들어야합니다.