+ Start a Discussion
Srini NandhiSrini Nandhi 

How to get URL of uploaded file from Amazon S3 Cloud Service using Salesforce..Using Rest API.

HI ALl,

I have a requirement with Salesforce with Amazon server with S3 Integration. I need to upload the files and same time download the files or URL of file form Amazon to  Salesforce.

I have uploaded the file using PUT method. Response i m receiving is like only [Status=OK and Statuscode=200] successful
but i m not getting any other things like uploadid or URL of the file.

i need URL of the File uploaded in Salesforce. Help me out from this

Thanks,

Reddy

pconpcon
Is there anything in the response body coming back from Amazon?  They should be providing additional information (probably in a JSON string) in the response to the PUT call.
Srini NandhiSrini Nandhi
Hi Pcon,

I am not getting anything in the Response body.  [Status=OK and Statuscode=200]  File got uploaded. 


Thanks,
Srini
pconpcon
Can you please provide the Apex code you are using to make the callout.  (Please make sure to obfuscate any authentication code)

NOTE: When adding code please use the "Add a code sample" button (icon <>) to increase readability and make it easier to reference.
Srini NandhiSrini Nandhi
in apex page i simply added one button and inputfile. 
I am doing in this way

  public PageReference SendRequest(){    
         
        binaryPdfString=String.ValueOf(inputFile);
        String key='XXXXXXXXXXXXXXXXXXXXX';
        String secret='xxxxxxxxxxxxxxxxxxxxxxxxxx';
        String formattedDateString= Datetime.now().formatGMT('EEE,   dd MMM yyyy HH:mm:ss z');
        String bucketname = '<bucketname>';
        String method = 'PUT';
        String filename = fname;
        HttpRequest req = new HttpRequest();
        req.setMethod(method);
        
        req.setHeader('Host','<bucketname>.s3.amazonaws.com');
        req.setEndpoint('https://<bucketname>.s3.amazonaws.com' + '/'+ bucketname + '/' + filename);
        req.setHeader('Content-Length', string.valueOf(binaryPdfString.length()));
        req.setHeader('Content-Encoding', 'UTF-8');
    //  req.setHeader('Content-Disposition', 'attachment'); 
        req.setHeader('Content-type', 'application/json');        
        req.setHeader('Connection','keep-alive');
        req.setHeader('Date', formattedDateString);
        req.setHeader('ACL','public-read');
        req.setBody(binaryPdfString);     
                  
        String stringToSign =
PUT\n\n'+'application/json\n'+formattedDateString+'\n/'+bucketname+'/'+bucketname+'/'+filename;
        String encodedStringToSign = EncodingUtil.urlEncode(stringToSign,'UTF-8');        
        String signed = createSignature(stringToSign,secret);
        String authHeader = 'AWS' + ' ' + key + ':' + signed;
        req.setHeader('Authorization',authHeader);
        String decoded = EncodingUtil.urlDecode(encodedStringToSign , 'UTF-8');        
       
        Http http = new Http();
        try {
             HTTPResponse res = http.send(req);          
             System.debug('*Resp:'+String.ValueOF(res.getBody()));                    
             System.debug('RESPONSE STRING: ' + res.toString());
             System.debug('RESPONSE STATUS: '+res.getStatus());
             System.debug('STATUS_CODE: '+res.getStatusCode());
             if(res.getStatusCode()==200 && res.getStatus()=='OK')
             {
                 success= filename +' File has uploaded Successfully.';
//this is executing 
                  inputFile=null;
             }

            } catch(System.CalloutException e) {
            system.debug('AWS Service Callout Exception: ' + e.getMessage());
        }

    return ApexPages.Currentpage();
}

 

    public string createSignature(string canonicalBuffer,String secret){
        string sig;
        Blob mac = Crypto.generateMac('HMACSHA1', blob.valueof(canonicalBuffer),blob.valueof(secret));
        sig = EncodingUtil.base64Encode(mac);  
        return sig;
    }
pconpcon
Looking at the documentation for the AWS file creationg, I believe the URL you need to store is
 
'https://<bucketname>.s3.amazonaws.com' + '/'+ bucketname + '/' + filename

it doesn't appear to generate a UUID for this url, so it should be the same place that you PUT it.
Srini NandhiSrini Nandhi
Hi Pcon,

I'm not understanding what you are saying. How to generate UUID in above Context. Can you give Sample code for that.

Thanks in advance

Thanks
Srini
pconpcon
What I'm saying is if you do a PUT to /mybucket/foo.jpg the URL for that file will be /mybucket/foo.jpg so with your code if someone loaded foo.jpg after the first one was created it would just overwrite that file.  If you want them to be unique you will need to generate a UUID [1] and prepend / append it to your PUT url.

[1] http://salesforce.stackexchange.com/questions/4073/how-to-generate-a-guid-uuid
usersfdc21usersfdc21
Hi Siri,

I am exactly working on the same requirement. I am able to upload the files in AWS S3 from salesforce. I need to get the uploaded file URL from Aws S3 and save in my contacts field. If you have done it please let me know. If I do it, I will update here. 

Thanks in advance.
pconpcon
As stated before, the file name that you do the PUT against will be the file name that you do you GET against to get the file.  I would recommend that you either generate a UUID inside of Salesforce, append that to the filename and do a PUT against that.  Otherwise you can use the built in Ids inside of Salesforce and use that.  For example if you are creating a single file for a contact, use the contact's Id as the filename (or prefix for that file).  You could also put the files in a folder that is the Id for the Contact record in salesforce.
usersfdc21usersfdc21
Hi Pcon,

Thanks for your reply.
Actually I have a bucket in S3 which is saving my videos. as of now, per contact we have only one video. so its not a problem if the new video over writes the existing one. 
I have created a formula field in contact object as below:
'https://s3-ap-southeast-2.amazonaws.com/sree.video.files/' & CASESAFEID(Id) &'.mp4'
sree.video.files is my bucket name which is storing videos.
& CASESAFEID(id) is returning contact Id and now I am able to get the AWS Url in to my Contact.Video_Url__c field.(formula field)
I am refering Video_Url field to my visual page so that my video can play in vf page. but video is not playing may be due to formula field.
When I copy paste the Url in different field which is Text, then the video is playing. 
Please advice. 

Thanks in advance.
usersfdc21usersfdc21
Hi Pcon,

It is working now. I am able to play the video in VF page.
Srini NandhiSrini Nandhi
Hey Sree,

Can you please share the code here . both uploading and Downloading (URL of the File uploaded) the uploaded file

Thanks
Srini
pconpcon
Srini, the code that you provided works for uploading files to S3 without an issue (I used it myself yesterday).  The URL of the file is exactly what you pass into your PUT request.  On line 17 of your code you set the endpoint, and that is going to be where you can download your file.
 
req.setEndpoint('https://<bucketname>.s3.amazonaws.com' + '/'+ bucketname + '/' + filename);

I would recommend that you simply store that URL in a variable and then you can store it on your record.  Either that or generate your URL in such a way that it can be derived from the record itself and then generate a formula.
usersfdc21usersfdc21
Hi srini,

I have user formula field in contact object. I have given the below code:
'https://s3-ap-southeast-2.amazonaws.com/sree.video.files/' & CASESAFEID(Id) &'.mp4'

I have used Aws S3 tool kit code to upload files.
I have created few buckets for different files. when ever customer updates his photo or video, I only need his latest updated files.
so the files updated in force.com web pages, over writes the existing files.
so there will be only one file for profile video for that particular contact. so I am appending his contact Id to the Aws path. I am able to play videos in website because I have given the contact field in the backend. and the contact field contains the latest path from Aws. 

whats ur mail Id Srini ?
 
usersfdc21usersfdc21
Thank you very much pcon.

and my URL looks like this:

'https://s3-ap-southeast-2.amazonaws.com/<bucketName>/'+contact.Id+'.mp4';
As I am in sydney, I use the URL as "s3-ap-southeast-2.amazonaws.com"
 
Srini NandhiSrini Nandhi
Hi Sree,

my mail id is
cnu.nandhikonda@gmail.com
Harendra Singh 19Harendra Singh 19
I am working to download file from amazon s3 using rest api call.
But getting error SignatureDoesNotMatch and message The request signature we calculated does not match the signature you provided. Check your key and signing method.

Can anyone pleae let me know what wrong I am doing here? 

public void getObject(){      
        String timestamp = Datetime.now().formatGmt('EEE, dd MMM yyyy HH:mm:ss Z');
        String bucket = 'testbucket';
        String key = 'Access Key';
        String method = 'GET';
        String secret = 'Secret key';
        
        String stringToSign = 'GET\n\n\n'+timestamp+'\n/'+bucket+'/'+'testfolder/Passport.pdf';
        String encodedStringToSign = EncodingUtil.urlEncode(stringToSign,'UTF-8');    
        
        Blob bsig = Crypto.generateMac('HMacSHA1',Blob.valueOf(encodedStringToSign),Blob.valueof(secret));
        String Signature = EncodingUtil.base64Encode(bsig);
        
        HttpRequest req = new HttpRequest();
        req.setMethod(method);
        req.setHeader('Host',bucket+'.s3.amazonaws.com');
        req.setEndpoint('https://'+bucket+'.s3.amazonaws.com'+'/'+bucket+'/'+foldername+'/'+'Passport.pdf');
        req.setHeader('Content-Encoding', 'UTF-8');
         req.setHeader('Authorization','AWS '+key+':'+signature);
        req.setHeader('Date',timestamp);
        
        Http http = new Http();
        HttpResponse res = http.send(req);
        system.debug('+++++Body is'+res.getBody());
       
    }
pconpcon
Harendra, You are missing some things in your request.  I would recommend reading over this article [1].

[1] http://blog.deadlypenguin.com/blog/2016/02/16/amazon-s3-attaching-a-file-in-salesforce/
Subrat kumar Ray 23Subrat kumar Ray 23
Hi Srikanth and Pcon,

I used the above code to upload files successfully. Below is the endpoint:
https://jstart-salesforce.s3.amazonaws.com/jstart-salesforce/0000001017/250x125-licenseplate_red.png

But, when I am trying to access the file by pasting the URL on browser I am getting error "<Code>AccessDenied</Code><Message>Access Denied</Message>". I put the URL on URL and Text type fields on Salesforce Asset object, but it does not display the image.

Thanks and Regards,
Subrat
Nagesh B 13Nagesh B 13
 i have one external object which is having text field DURL__C. which contains URL. if i take any  DURL__C Value  and pasted in the browser one image is getting downloaded into my local system. My Requirement is i should get this image and wanna upadate profile pic of a User  using connect API. 

please need help on this
Nagesh B 13Nagesh B 13
i used document object , but getting blank image
Jasveer SinghJasveer Singh
Hi SrikanthVivaram
                            Could you please share s3 code to mee... its very urgent to me
Thanks & Regards
Jasveer Singh
info.jasveer@gmail.com
Divesh BafnaDivesh Bafna
Hi,
Can anyone help me in providing a link to a document or a sample code which explains on how to read csv files stored on s3 bucket from salesforce?
Thanks!
S3-LinkS3-Link
S3- Link is FREE App for Salesforce - Amazon Connector. Its also available on Appexchange. 
 

    Attach file related to any Salesforce object on Amazon.
    5 GB free storage for one year.
    Multiple file uplaod.
    No file size limit for upload.
    File access control capabiliy.
    Track file downloads by users.
    File exlorer capability.

https://appexchange.salesforce.com/listingDetail?listingId=a0N3000000CW1OXEA1

Here is our email address. Let us know if you have any query.
support@neiloncloud.com

Thanks.
Rahul Gawade 18Rahul Gawade 18
Hi all, 

I am also getting the issue same as @Subrat kumar Ray 23 when i hit the URL.

I am getting error "<Code>AccessDenied</Code><Message>Access Denied</Message>".

Thanks in Advance.

 
Sonam MeshramSonam Meshram
Hello All,
I came across the newly developed app in AppExchange named Drag, Drop & Upload Files to Amazon S3 for this am using the same and its very easy to understand and having advanced features like you can delete/view your files from salesforce, and also provide some additional customization.
Please have look: https://sforce.co/34y12sL