将图像上传到S3存储桶 [英] Uploading image to S3 bucket

查看:92
本文介绍了将图像上传到S3存储桶的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Android中将图像上传到Amazon s3存储桶?我有用于上传的密钥和访问密钥,但仍然无法执行.这是我的代码

How to upload an image to Amazon s3 bucket in android?.I am having secret key and access key for uploading but still not able to do.Here is my code

        protected String doInBackground(String... params) {
            publishProgress("Sleeping..."); // Calls onProgressUpdate()
            String date = (DateFormat.format("dd-MM-yyyy hh:mm:ss", new java.util.Date()).toString());
            String ACCESS_KEY = "",
                    SECRET_KEY = "",
                    MY_BUCKET = "retailappimages",
                    OBJECT_KEY = unique_id+"-"+date;
            AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY);
            AmazonS3 s3 = new AmazonS3Client(credentials);
            java.security.Security.setProperty("networkaddress.cache.ttl", "60");
            s3.setRegion(Region.getRegion(Regions.AP_SOUTHEAST_1));
            s3.setEndpoint("https://s3-ap-southeast-1.amazonaws.com/");

            Log.i("path", myUri.getPath());


            TransferManager tx = new TransferManager(credentials);
            myUpload = tx.upload(MY_BUCKET, OBJECT_KEY, new java.io.File(getBitmapUri(img_product).getPath()));


            return resp;
        }

推荐答案

下面是示例代码将您的赢钥匙&代码中的bucket_name:

Here is sample code Put your won keys & bucket_name in code:

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.services.s3.model.ResponseHeaderOverrides;
import com.worldofmoms.networklib.R;
import com.worldofmoms.networklib.listeners.IRequestListener;
import com.worldofmoms.networklib.utils.helpers.LocalLog;
import java.io.File;

public class UploadImageTask  extends AsyncTask<String, Void, String> {
    private ProgressDialog dialog;
    private IRequestListener<Object> mListener;
    private String mRequestTag;
    Context mContext;

    public UploadImageTask(Context context,String requestTag, IRequestListener<Object> listener)
    {
        mContext=context;
        mRequestTag=requestTag;
        this.mListener=listener;
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = ProgressDialog.show(mContext, null, "", true);
        dialog.setContentView(R.layout.loaders_progress_dialog);
        dialog.setCancelable(false);
    }

    @SuppressWarnings("unused")
    @Override
    protected String doInBackground(String... params) {
        String path = params[0];
        return sendImageToAmazonS3Server(path);
    }

    @Override
    protected void onProgressUpdate(Void... unsued) {}

    @Override
    protected void onPostExecute(String sResponse) {
        if (dialog!=null && dialog.isShowing()) {
            dialog.dismiss();
        }
        this.mListener.onRequestSuccess(mRequestTag, sResponse);
    }

    private String sendImageToAmazonS3Server(String Filepath){
        //String MY_ACCESS_KEY_ID 
        String MY_ACCESS_KEY_ID = "Put Access key";

        //String MY_SECRET_KEY 
        String MY_SECRET_KEY = "Put SECRET_KEY ";


        //String MY_PICTURE_BUCKET 
        String MY_PICTURE_BUCKET = "bucketName";
        //String MY_PICTURE_BUCKET = "wom-profilepics-test";

        String rootUpload = Filepath;
        File file = new File(rootUpload);
        if (file.exists()) {
            String fileExtension="jpg";

            String imageNAME = String.valueOf(System.currentTimeMillis());
            String fileNameToUpload = imageNAME+"."+fileExtension;
            fileNameToUpload=fileNameToUpload.trim();
            try {
            AmazonS3Client s3Client = new AmazonS3Client(new BasicAWSCredentials(MY_ACCESS_KEY_ID, MY_SECRET_KEY));
            // create bucket
            //s3Client.createBucket(MY_PICTURE_BUCKET);
            InputStream input = new URL("https://hi.co/bundles/hitomain/images/hi_big.png?v=1448090952").openStream();
            ObjectMetadata objectMetadata = new ObjectMetadata();
            PutObjectRequest por = new PutObjectRequest(MY_PICTURE_BUCKET,fileNameToUpload,input,objectMetadata);
            por.setCannedAcl(CannedAccessControlList.PublicRead);
            PutObjectResult result = s3Client.putObject(por);

                 LocalLog.d("PATH", "" + fileNameToUpload);

                /*LocalLog.d("putting Object result ",""+ result.getETag()
                        //result.
                        + " MD5 " + result.getContentMd5());*/

                ResponseHeaderOverrides override = new ResponseHeaderOverrides();
                override.setContentType("image/jpeg");

                /*GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest( MY_PICTURE_BUCKET,imageNAME );
                urlRequest.setExpiration( new Date(System.currentTimeMillis() + 3600000));  // Added an hour's worth of milliseconds to the current time.
                urlRequest.setResponseHeaders(override);
                URL url = s3Client.generatePresignedUrl( urlRequest );*/
                //LocalLog.d(" S3 SERVER IMAGE PATH = ",""+url.toString());
                String filePathOnServer = "http://"+MY_PICTURE_BUCKET+".s3.amazonaws.com/"+fileNameToUpload;
                LocalLog.d(" S3 SERVER IMAGE PATH = ",""+filePathOnServer);
                return filePathOnServer;
            } catch (Exception e) {
                LocalLog.printStackTrace(e);
                return "";
            }
        } else {
            return "";
        }
    }
}

这篇关于将图像上传到S3存储桶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆