简体   繁体   English

移动后端入门 - 上传到AppEngine Blobstore

[英]Mobile Backend Starter - Upload to AppEngine Blobstore

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

Sharing my expirience with Mobile Backend Starter. 与Mobile Backend Starter分享我的经验。

To obtain uploading and downloading urls you need to add this two methods to CloudBackend.java class to make urls accessible from the Activity: 要获取上传和下载网址,您需要将这两种方法添加到CloudBackend.java类,以便从活动中访问网址:

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

Then you can use urls to stream bytes to Google Cloud Storage with the helping of standard client libraries. 然后,您可以使用网址通过标准客户端库将字节流式传输到Google云端存储。

Below I'll give you examples how to use them. 下面我将举例说明如何使用它们。

For uploading file to the Google Cloud Storage you may use something similar to this: 要将文件上传到Google云端存储,您可以使用与此类似的内容:

Activity 活动

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

AsyncTask 的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 class is not included into android standard libraries so you need to download httpclient and include into your project. MultipartEntityBuilder类不包含在android标准库中,因此您需要下载httpclient并将其包含到您的项目中。

Pay attention to this line String url = uploadUrl.split("&Signature")[0]; 注意这一行String url = uploadUrl.split("&Signature")[0]; where I am cutting off url signature. 我在哪里切断网址签名。 (With url signature I am getting 503 Internal Server Error but without it everything works as expected. I do not why this happens.) (使用url签名我得到503 Internal Server Error但没有它一切都按预期工作。我不知道为什么会发生这种情况。)

For downloading you can use this snippet: 要下载,您可以使用以下代码段:

Activity 活动

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

AsyncTask 的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));   
    }   
}

NOTE: To use Google Cloud Storage you need to enable billing. 注意:要使用Google云端存储,您需要启用结算功能。 Also you need to create bucket in GCS. 您还需要在GCS中创建存储桶。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM