how to upload image to s3 bucket

I am trying to upload an image named 'quotes.png' to s3 bucket in my Ionic 2 apps (WITHOUT using node) but it says 'Network Failure'.

This is how my codes look like (with sensitive info omitted):

import AWS from 'aws-sdk';
import S3 from 'aws-sdk/clients/s3';

AWS.config.update({ accessKeyId: 'myaccesskeyid', secretAccessKey: 'mysecretaccesskey' })
var s3 = new AWS.S3();
var params = {
        Bucket: 'mybucketname',
        Key: 'assets/img/quotes.png',
        Body: "hello"
    };
    s3.putObject(params, function (err, res) {

        if (err) {

            console.log(err);
        } else {
              debugger;
            console.log("Successfully uploaded data to myBucket/myKey");
        }
    });

(UPDATED)This is the details of the error:

XMLHttpRequest cannot load https://mybucket-name.s3-ap-southeast-
1.amazonaws.com/assets/img/quotes.png. Response to preflight request doesn't 
pass access control check: No 'Access-Control-Allow-Origin' header is 
present on the requested resource. Origin 'http://localhost:8100' is 
therefore not allowed access. The response had HTTP status code 403.

Error: Network Failure
at XMLHttpRequest.<anonymous> (xhr.js:52)
at t.invokeTask (polyfills.js:3)
at Object.onInvokeTask (ng_zone.js:227)
at t.invokeTask (polyfills.js:3)
at e.runTask (polyfills.js:3)
at XMLHttpRequest.invoke (polyfills.js:3)

NOTE: I am NOT using node js in my Ionic 2 app. I am using Parse JavaScript SDK, AWS S3, AWS EC2, Elastic beanstalk and Ionic 2 with Angular 2.

So the question: Did I write my code properly/is there something wrong with my code? Thanks :)

Upvotes: 0

Views: 892

Answers (2)

John Hanley
John Hanley

Reputation: 81386

You need to specify the region where the bucket is located in AWS.config.

Example:

AWS.config.update({region: 'us-west-2'});

Insert this line before the call to new AWS.S3().

Upvotes: 1

Aashish Prajapat
Aashish Prajapat

Reputation: 43

Here is the latest code of upload images using s3 bucket in aws

var AWS = require('aws-sdk');
var fs = require('fs');
var path = require('path');
var multerS3 = require('multer-s3');

AWS.config.update({
accessKeyId: "",
secretAccessKey: "",
region:''
});

 router.post('/upload_images_s3', upload.single('image'),  (req,res,next) => {
        res.json('Successfully uploaded  files!')
 });
 
 var maxSize = 1024 * 1024 * 50;
var  rootFolder = path.resolve(__dirname, './');
var s3 = new AWS.S3({params: {Bucket: 'keyfi'}});
var upload = multer({
    storage: multerS3({
      s3: s3,
      bucket: 'keyfi/images',
      acl: 'public-read-write',
      limits: {
        fileSize: maxSize
    },
      metadata: function (req, file, cb) {
        cb(null,{fieldName:file.originalname});
        console.log(file);
      },
      key: function (req, file, cb) {
       
        cb(null,file.originalname)
      }
    })
  })

Upvotes: 0

Related Questions