【问题标题】:Mobile Backend Starter - Upload to AppEngine Blobstore移动后端启动器 - 上传到 AppEngine Blobstore
【发布时间】:2014-02-05 13:01:26
【问题描述】:

如何使用 Mobile Backend Starter 或 Google Cloud Endpoints 将文件从 Android 上传到 Google App Engine Blobstore?

【问题讨论】:

    标签: java android google-app-engine google-cloud-endpoints blobstore


    【解决方案1】:

    与 Mobile Backend Starter 分享我的经验。

    要获取上传和下载的url,你需要将这两个方法添加到CloudBackend.java类中,使url可以从Activity访问:

    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;
        }
    

    然后,您可以在标准客户端库的帮助下使用 url 将字节流式传输到 Google Cloud Storage。

    下面我将举例说明如何使用它们。

    要将文件上传到 Google Cloud Storage,您可以使用类似于以下内容的内容:

    活动

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

    异步任务

    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 类未包含在 android 标准库中,因此您需要下载 httpclient 并包含到您的项目中。

    注意这一行 String url = uploadUrl.split("&amp;Signature")[0]; 我正在切断 url 签名。 (使用 url 签名我得到503 Internal Server Error 但没有它一切都按预期工作。我不知道为什么会发生这种情况。)

    下载你可以使用这个sn-p:

    活动

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

    异步任务

    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 中创建存储桶。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-25
      • 2013-05-30
      • 1970-01-01
      • 2014-12-09
      • 2012-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多