I'm uploading a file using Amazon's AWS SDK (S3), and everything is working fine. Below is my code:
final AWSCredentials credentials = new AWSCredentials() {
#Override
public String getAWSAccessKeyId() {
return "...myAccessKey...";
}
#Override
public String getAWSSecretKey() {
return "...mySecretKey...";
}
};
final StaticCredentialsProvider credentialsProvider = new StaticCredentialsProvider(credentials);
final TransferManager transferManager = new TransferManager(credentialsProvider);
final Upload upload = transferManager.upload(Config.AWS_IMAGE_BUCKET, "images/" + file.getName(), file);
Problem is, whenever I upload something like this, the permissions are not set to public, so I can't use them in my app.
How can I set the file permissions from my code so that it's viewable by public?
Thanks!
You need to provide a PutObjectRequest with the ACLs you want when you call upload.
Choose appropriate ACL policy when you put file in to the bucket.
It can be one of the following option:
1) ACL_AUTHENTICATED_READ
Allow read access to authenticated users.
2) ACL_PRIVATE
Allows only private access to the file.
3) ACL_PUBLIC_READ.
Allows public read access to the file.
4) ACL_PUBLIC_READ_WRITE
Allows public read write access to the file when you write files onto the bucket.
Related
I am new to aws s3. I have some images in my aws s3 bucket. How can i retrieve the images and display it in android app.
If anybody knows please tell.
Your retrieval URL should look something like below considering that your bucket has no access restrictions.
String imagePath = https://s3.YOUR_BUCKET_REGION.amazonaws.com/YOUR_BUCKET_NAME/FILE_NAME.jpg
For example,
String imagePath = https://s3.eu-west-2.amazonaws.com/my_photos_bucket/my_pic.jpg
Use Glide or Picasso to load the image to your ImageView
You can use code similar to below to download a list of files in a bucket
AmazonS3Client s3 = create you AmazonS3Client
ObjectListing listing = s3.listObjects( bucketName, prefix );
List<S3ObjectSummary> summaries = listing.getObjectSummaries();
while (listing.isTruncated()) {
listing = s3.listNextBatchOfObjects (listing);
summaries.addAll (listing.getObjectSummaries());
}
for(S3ObjectSummary objectSummary : summaries) {
String key = objectSummary.getKey();
//download the file with object key = key
}
i am creating an Android App within AWS mobile Hub, i would like to do know is it possible when a user Signs up to my Application that an S3-Bucket or even a Folder within an S3 bucket is created only for that user account ?
Yes, you can use PutObjectRequest(bucketName, keyName, file) to achieve your use case.
Create S3 folder
With AWS S3 Java SDK , just add "/" at the end of the key name, it will create empty folder.
var folderKey = key + "/"; //end the key name with "/"
Sample code:
final InputStream im = new InputStream() {
#Override
public int read() throws IOException {
return -1;
}
};
final ObjectMetadata om = new ObjectMetadata();
om.setContentLength(0L);
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, im, om);
s3.putObject(putObjectRequest);
I am using Android aws sdk 3.2 for uploading images from Android phone to amazon s3, this is working fine but i want to compress image before uploading to amazon s3.
I have explored a lot and found few solutions.
Compress image on client side and make copy of that file and upload to S3 after uploading delete that file.
Compress image on client side and upload that image to EC2 server and then upload same image to s3 from EC2.
I am using this code provided by amazon :-
private static AmazonS3Client getS3Client(Context context) {
if (sS3Client == null) {
sS3Client = new AmazonS3Client(getCredProvider(context.getApplicationContext()));
}
return sS3Client;
}
/**
* Gets an instance of the TransferUtility which is constructed using the
* given Context
*
* #param context
* #return a TransferUtility instance
*/
public static TransferUtility getTransferUtility(Context context) {
if (sTransferUtility == null) {
sTransferUtility = new TransferUtility(getS3Client(context.getApplicationContext()),
context.getApplicationContext());
}
return sTransferUtility;
}
private static CognitoCachingCredentialsProvider getCredProvider(Context context) {
if (sCredProvider == null) {
sCredProvider = new CognitoCachingCredentialsProvider(
context.getApplicationContext(),
Constants.POOL_ID,
Regions.AP_NORTHEAST_1);
}
return sCredProvider;
}
getTransferUtility(context).upload(
"bucket name", uuid,
new File(path));
I want to know does amazon itself provide the facility to compress file then upload or is there a better way of uploading file to s3 after compression?
You are right about AWS S3. It doesn't support compression. It only accepts file as it is. What you proposed are valid solutions. Unfortunately, the SDK can't help you with compression. Though you can use TransferUtility for upload.
I want to upload image on Google Cloud Storage from my android app. For that I searched and found that GCS JSON Api provides this feature. I did a lot of research for Android sample which demonstrates its use. On the developer site they have provided code example that only support java. I don't know how to use that API in Android. I referred this and this links but couldn't get much idea. Please guide me on how i can use this api with android app.
Ok guys so I solved it and got my images being uploaded in Cloud Storage all good.
This is how:
Note: I used the XML API it is pretty much the same.
First, you will need to download a lot of libraries.
The easiest way to do this is create a maven project and let it download all the dependencies required. From this sample project :
Sample Project
The libraries should be:
Second, you must be familiar with Cloud Storage using the api console
You must create a project, create a bucket, give the bucket permissions, etc.
You can find more details about that here
Third, once you have all those things ready it is time to start coding.
Lets say we want to upload an image:
Cloud storage works with OAuth, that means you must be an authenticated user to use the API. For that the best way is to authorize using Service Accounts. Dont worry about it, the only thing you need to do is in the API console get a service account like this:
We will use this service account on our code.
Fourth, lets write some code, lets say upload an image to cloud storage.
For this code to work you must put your key generated in step 3 in assets folder, i named it "key.p12".
I don't recommend you to do this on your production version, since you will be giving out your key.
try{
httpTransport= new com.google.api.client.http.javanet.NetHttpTransport();
//agarro la key y la convierto en un file
AssetManager am = context.getAssets();
InputStream inputStream = am.open("key.p12"); //you should not put the key in assets in prod version.
//convert key into class File. from inputstream to file. in an aux class.
File file = UserProfileImageUploadHelper.createFileFromInputStream(inputStream,context);
//Google Credentianls
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE))
.setServiceAccountPrivateKeyFromP12File(file)
.build();
String URI = "https://storage.googleapis.com/" + BUCKET_NAME+"/"+imagename+".jpg";
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
GenericUrl url = new GenericUrl(URI);
//byte array holds the data, in this case the image i want to upload in bytes.
HttpContent contentsend = new ByteArrayContent("image/jpeg", byteArray );
HttpRequest putRequest = requestFactory.buildPutRequest(url, contentsend);
com.google.api.client.http.HttpResponse response = putRequest.execute();
String content = response.parseAsString();
Log.d("debug", "response is:"+response.getStatusCode());
Log.d("debug", "response content is:"+content);} catch (Exception e) Log.d("debug", "Error in user profile image uploading", e);}
This will upload the image to your cloud bucket.
For more info on the api check this link Cloud XML API
Firstly, You should get the below information by registering your application in the GCP console.
private final String pkcsFile = "xxx.json";//private key file
private final String bucketName = "your_gcp_bucket_name";
private final String projectId = "your_gcp_project_id";
Once you get the credentials, you should put the private key (.p12 or .json) in your assets folder. I'm using JSON format private key file. Also, you should update the image location to upload.
#RequiresApi(api = Build.VERSION_CODES.O)
public void uploadImageFile(String srcFileName, String newName) {
Storage storage = getStorage();
File file = new File(srcFileName);//Your image loaction
byte[] fileContent;
try {
fileContent = Files.readAllBytes(file.toPath());
} catch (IOException e) {
e.printStackTrace();
return;
}
if (fileContent == null || fileContent.length == 0)
return;
BlobInfo.Builder newBuilder = Blob.newBuilder(BucketInfo.of(bucketName), newName);
BlobInfo blobInfo = newBuilder.setContentType("image/png").build();
Blob blob = storage.create(blobInfo, fileContent);
String bucket = blob.getBucket();
String contentType = blob.getContentType();
Log.e("TAG", "Upload File: " + contentType);
Log.e("File ", srcFileName + " uploaded to bucket " + bucket + " as " + newName);
}
private Storage getStorage() {
InputStream credentialsStream;
Credentials credentials;
try {
credentialsStream = mContext.getAssets().open(pkcsFile);
credentials = GoogleCredentials.fromStream(credentialsStream);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return StorageOptions.newBuilder()
.setProjectId(projectId).setCredentials(credentials)
.build().getService();
}
google-api-java-client is a good web service api client on Android, however I mean a problem and spend lots of time on it.
I want to upload a file via POST method, so I study the google-drive API source code, but it uses the media uploader to upload file to google drive.
so how to upload a file via POST method in google-api-java-client?
for example Imgur upload API method has two require parameter.
suppose a upload file API written in google-api-java-client like this, but i have no idea how should I fill in the 'image' field which marked ???
public class ImgurImage extends GenericJson {
#com.google.api.client.util.Key("key")
private String mKey;
#com.google.api.client.util.Key("image")
private ??? mImage
}
public class Upload extends JsonHttpRequest {
private static final String REST_PATH = "/2/upload.json"
private Upload(ImgurImage content) {
super(ImgurClient.this, HttpMethod.POST, REST_PATH, content);
}
public void execute() throws IOException {
executeUnparsed();
}
}
I recommend taking a look at our Drive API sample at http://samples.google-api-java-client.googlecode.com/hg/drive-cmdline-sample/instructions.html
Here's a code snippet:
private static final java.io.File UPLOAD_FILE = new java.io.File(UPLOAD_FILE_PATH);
/** Uploads a file using either resumable or direct media upload. */
private static File uploadFile(boolean useDirectUpload) throws IOException {
File fileMetadata = new File();
fileMetadata.setTitle(UPLOAD_FILE.getName());
InputStreamContent mediaContent = new InputStreamContent("image/jpeg", new BufferedInputStream(
new FileInputStream(UPLOAD_FILE)));
mediaContent.setLength(UPLOAD_FILE.length());
Drive.Files.Insert insert = drive.files().insert(fileMetadata, mediaContent);
MediaHttpUploader uploader = insert.getMediaHttpUploader();
uploader.setDirectUploadEnabled(useDirectUpload);
uploader.setProgressListener(new FileUploadProgressListener());
return insert.execute();
}
I use httpClient and I use FileBody to send a file to a server, as part of a MultiPartEntity. This works for Picasa, Flickr, etc.
it looks like you adopted a sample that was uploading text (json in content, json in the REST URL endpoint) and used it to attempt image upload ( upload(ImgurImage) ).
So, look at the source for the 'GenericJson.upload(ImgurImage)'...
See what this method does when it sets the 'content' field prior to calling 'exec' on the POST.
Understand that these frameworks will allow either strings and text in content or allow bitmaps ( bytes ) for images and audio type uploads.
Look for a handler that sets the 'content' and understand how it handles both bytes and strings for the json sample.
that should help you use the framework you have chosen.